Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • ***Latest features introduced with C# 4.0 and above versions***

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 507
    Comment on it

    Latest features introduced with C# 4.0 and above versions

    C# 4.0 is a version of the C# programming language that was released on April 11, 2010. Microsoft released the 4.0 runtime and development environment Visual Studio 2010.

    Microsoft breaks the following features in C# 4.0 :- Named and Optional Parameters Dynamic Support Variance COM Interop

    Named and Optional Parameters

    The reason for introducing optional parameters to C# 4.0 is in order to better support COM interoperability. This is a very good feature that allows us to omit parameters whenever they are not required, or send parameters with default values. Optional parameters allows us to give a method parameter a default value so that we do not have to specify it every time we call the method.

    Example:-

    public void CreateNewStudent (string name, int studentid = 0, int year = 1)

    The above method can be called in any of the following ways:-

         CreateNewStudent("Sukanya");          //Equivalent to Sukanya,0,1 
         CreateNewStudent("Prakash", 16);    //Equivalent to Prakash,16,1
         CreateNewStudent("Pinal", 40, 2);     //Equivalent to Pinal,40,2

    In the above code, it is mandatory to pass the name, but the remaining two parameters are optional. If we do not pass any of the values in those parameters, then the default values are passed.

    Note: The Optional Parameters must be placed after the required parameters, or else the C# compiler will show a compile time error.

    Named arguments is a way to provide an argument, using the name of the desired parameter, instead of depending on its position in the parameter list. Now, if we want to omit the studentid parameter value in the above code, but specify the year parameter, It can be done as follows:-

     CreateNewStudent(Jacob,year:2);

    All of the following are also valid calls:-

      CreateNewStudent(name: "Andrew", studentid: 30, year: 2);
      CreateNewStudent("Vamshi", studentid: 4);
      CreateNewStudent(year:2, name:"Hima", studentid: 4); 

    Named arguments is a best way to write self documenting calls to our existing methods even if they are not using optional parameters. Using Named arguments we can not only change the name but can also change the position of the parameters if desired.

    ***Dynamic Support***

    Let us understand this with the help of an example.

    Example-

    Following is a class with two properties:

     Public class Customer
         {
           Public string FirstName{ get; set; }
           Public string LastName{ get; set; }
         }

    Consider the following code:

        Public object GetCustomer()
             {
                Customer cust= new Customer();
                return cust;
             }

    The above method will return an object but not the Customer, So if we want to use this method we have to use typecasting..

     Customer cust= GetCustomer() as Customer;
            if(cust!=null)
            {
               Cust.FirstName=Henry;
            }
    But what if we dont want to typecast it or if we dont know the type of the object returned. To handle such situations Dynamic Support was inroduced in C# 4.0. The dynamic keyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime.

    Example:

       Using Dynamic Support:
      dynamic cust= GetCustomer(); 
      cust.FirstName=Henry;
      cust.LastName=Dousaz;

    We did not need to cast nor declare cust as type Customer. Because we declared it dynamic, the runtime takes over and then searches and sets the FirstName and LastName property for us.

    ***Variance***

    The term "variance" refers to the ability to use one type where another was specified. Variance allows casting of generic types to the base types. Example: IEnumerable(A) will be implicitly convertible to IEnumerable(B) if A can be implicitly converted to B.


      namespace CSharpNewFeatures
                 {
                    class Program
                    {
                       static void Main(string[] args)
                        {
                          // Say we have a list of strings
                            IList(string) arrNames = new List(string)();
                         // Now we can convert it into an Enumerable collection
                          IEnumerable(object) objects = arrNames;
                        }
                    }
                  }

    ***COM Interop***

    Let us understand this with the help of following :

    Example:

    using Microsoft.Office.Interop;
    using Microsoft.Office.Interop.Word;
    object foo=MyFile.txt;
    object bar=Missing.Value;
    object optional=Missing.Value;
    Document doc= (Document)Application.GetDocument( ref foo, ref bar, ref optional);

    In the code above there are three problems...

    1. We have to declare all our variables as objects and pass them with ref keyword.
    2. We cannot omit parameters and must also pass the Missing.Value even if we are not using it.
    3. We are using huge interop assemblies just to make one method call.

      C# 4.0 has allowed us to write the above code in much simpler form inorder to overcome above mentioned problems:

      Using Microsoft.Office.Interop.Word;
      Var doc= Application.GetDocument(MyFile.txt);
      Doc.CheckSpelling();

    Behind the scene the interop assembly that is generated will only include the interop code we are actually using in our application, This will cut down the application size tremendously.


    C# recent version 5.0 was released on August 15, 2012 with .NET Framework 4.5 and Visual Studio 2012.

    The two main features introduced in C# 5.0 are Async Programming Caller Information

    ***Async Programming***

    This feature helps us to write asynchronous code more easily as synchronous code. Earlier for writing an asynchronous code, we need to define callbacks to capture what happens after an asynchronous process finishes, which makes our task complicated. Async feature introduces two keywords async and await. Both the keywords are used in a combination of each other. Hence, an await operator is applied to one or more than one expressions of an async method. An async method returns a Task or Task that represents the ongoing work of the method.

    Example: Suppose that we have a Windows Forms application and we want to download an image from the web and display it in the picture box. The following code does that synchronously.

     Private void button_Click(object sender, EventArgs e)
     {
       WebClient client = new WebClient();
       byte[ ] imageData = client.DownloadData(imageurl);
       this.pictureBox.Image = Image.FromStream(newMemoryStream(imageData));                 
     }

    Now suppose that internet is slow, it takes 30 seconds to download the image therefore during this time the application becomes unresponsive and if the user is impatient he/she can terminate the application. So in order to resolve this situation we have to download the image asynchronously which is done with the help of async and await keywords.

      Private async void button_Click (object  sender , EventArgs  e)
       {
          WebClient client = new WebClient();
          byte[ ] imageData = await client.DownloadDataTaskAsync(http://imageurl);
          this.pictureBox.Image = Image.FromStream(new MemoryStream(imageData));                    
       }

    In this code we have added three things i.e.

    async keyword-----that tells the compiler that this method may contain the await keyword. DownloadDataTaskAsync method of the WebClient class----- that downloads the image asynchronously.
    await keyword----- that returns the control to the caller method i.e. if we want to release the UI thread until the download is complete, the await keyword does exactly that. Once the awaited operation completes, the method resumes back.

    ***Caller Information***

    Caller Information helps in tracing, debugging and creating diagnose tools. It also helps us to write duplicate codes i.e. the codes written for the same purpose such as logging and tracing.

    Caller method provides following information:

    CallerFilePathAttribute
    (Full path of the source file that contains the caller. This is the file path at compile time.)

    CallerMemberNameAttribute
    (Line number in the source file at which the method is called.)

    CallerMemberNameAttribute
    (Method or property name of the caller.)

    Example:

      Using System;
      Using System.Cllections.Generic;
      Using System.Linq;
      Using System.Text;
      Using System.Threading.Tasks;
      Class Example
      {
              Static void Main(string[ ] args)
              {
                Console.WriteLine(Main method start);
                Log(Main);
                MethodB();
                MethodA();
                Console.WriteLine(Main method end);
             }
    
            Static void MethodA()
             {
               Log(MethodA);
               MethodB();
             }
            Static MethodB()
            {
            }
          Static void Log(string method)
          {
           Console.WriteLine({0} called MethodB at {1}, method, DateTime.Now);
          }
      }

    In this code we can see that Log() method is invoked for logging therefore we can change the above code as follows:

      Using System;
      Using System.Cllections.Generic;
      Using System.Linq;
      Using System.Text;
      Using System.Threading.Tasks;
      Class Example
      {
            Static void Main(string[ ] args)
             {
               Console.WriteLine(Main method start);
               MethodB();
               MethodA();
               Console.WriteLine(Main method end);
             }
    
            Static void MethodA()
            {
              MethodB();
            }
    
            Static MethodB( [CallerMemberName] string memberName = ,   [CallerFilePath] string sourceFilePath = , [CallerLineNumber] int sourceLineNumber = 0)
              {
                 Log(memberName);
              }
    
          Static void Log(string method)
           {
            Console.WriteLine({0} called MethodB at {1}, method, DateTime.Now);
           }
      }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: