C# 6.0 New Features

With the release of visual studio 2015 preview we are ready to experience new version of C#. C# 6.0 include some syntactical improvement from earlier versions that makes code lighter and helpful in reducing lines of code. C# 6 also include some amazing features.

Key Featuers

Below section describes each feature in detail.

Auto Property Initialization

Prior to coming C# 6, if we have to provide default value for properties then we need to initialize properties in constructor of that class, but now in C# 6 Auto property initializer will allow you to set default value of property as part of property deceleration.

Below is the code sample describe auto property initialization syntax.

Older Approach

public class Student
{
        /// 
        /// Default constructor to initialize properties
        /// 
        public Student()
        {
            this.Id = 1;
            this.Name = "Ashish";
            this.Grade = "A++";
            this.JoiningDate = DateTime.Now.Date;
        }
 
        public int Id { get; set; }
        public string Name { get; set; }
        public string Grade { get; set; }
        public DateTime JoiningDate { get; set; }
 }

New approach

/// Class using auto propery initialization 
    public class Student
    {
        public int Id { get; set; } = 1;
        public string Name { get; set; } = "Ashish";
        public string Grade { get; set; } = "A++";
        public DateTime JoiningDate { get; set; } =DateTime.UtcNow;
    }

Dictionary initialization

Now there is new way to initialize Dictionary collection by removing curly braces for each item, helping to reduce lines of code and more readable.

Older Approach

Dictionary<int, string> students = new Dictionary<int, string>()
            {
                { 1, "Ashish" },
                { 2, "Salman" },
            };

New approach

Dictionary<int, string> studentsNew = new Dictionary<int, string>()
            {
                [1] = "Ashish",
                [2] = "Salman",
            };

String interpolation (using $ sign)

String interpolation feature allow to format string more easily. Earlier we use String.Format () to format string in any particulate format. Using String. Format is more error prone as it uses placeholder {0}, {1} and then replacing these placeholder values with actual values.

Older Approach

Console.WriteLine(String.Format("{0} is reading {1}",name,blogName));

Now using string interpolation we can directly use variable or even expression on place where we need to place instead of using placeholders.

New approach

Console.WriteLine($"{name} is reading {blogName}");

Static using syntax

Using static feature allow to import all static member of type (class) so we can use them without qualifying type name before accessing the static member. For example suppose we want to use System.Math class member frequently in our program then we need to apply Math prefix every time we call static members of System.Math (e.g. Math.Sqrt(5), Math.Pow(2,3), Math.Round(16.66) etc).

Older Approach

class TestClass
{
    static void Main(string[] args)
    {
        Console.WriteLine(Math.Sqrt(3*3 + 4*4)); 
        Console.WriteLine(Math.Round(16.66)); 
        Console.WriteLine(Math.Pow(2,3)); 
    }
}

Now using static we can write same code more cleanly and easily.

New approach

using System;
using static System.Console;
using static System.Math;
class TestClass
{
    static void Main(string[] args)
    {
        WriteLine(Sqrt(3*3 + 4*4)); 
        WriteLine(Round(16.66)); 
        WriteLine(Pow(2,3)); 
    }
}

nameOf method

C# 6.0 provide new nameOf method to return name of any program element. This feature may be useful in cases where we want to use the name of any programming element to raise an event that uses name of programming element. Though we may use string literal to pass name but this leads in error-prone situation may be due to incorrect spelling or any other. Using string may also not support refactoring. To overcome this finally we have nameOf() to get name of programming element.

Example:

string firstName = "Modern Pathshala";
Console.WriteLine(string.Format("Variable Name = {0}"),nameOf(firstName)); 

Output: firstName

Exception filter

Exception filter are now available with C# 6.0 though they were already there in VB and F#. Exception filters enable conditional execution of Catch block. We can define different catch block for each specific condition and catch block will get executed accordingly.

Example

try
       {
           // to to
           throw new Exception("CustomException");
       }
       catch (Exception ex) if(ex.InnerException !null)
       {
           //Execute code if condition matches
       }
       catch(Exception ex) if (ex.InnerException =="some message")
       {
           //Execute code if this condition matches
       }

In the above example the first catch block will execute if inner exception is null.

Lambda expression debugging

Many of us worked with LINQ and lambda expression may have gone through the exception message “Expression cannot contain lambda expressions” while trying to debug the expression containing lambda. Now out of the box we are ready to experience expression debugging with C# 6.0. Now also there are some limitations with lambda expression debugging in C# 6. One of them is currently it doesn’t support lambda expressions that require calls to native functions. We are looking forward, for this feature from Microsoft as Microsoft team is already working on same.

Async / await in error handling

Now C# 6.0 allows to use await functionality in error handling. If any operation performs async operation in try block then catch and finally block wait for operation to be completed and we may perform asynchronous operation in catch and finally block.

try
{
   var result = await Resource.AsyncOperation();    
} 
catch(ResourceException e)
{
    await Resource.LogErrorAsync(res, e);   
}
finally
{
    if (res != null) await res.CloseAsync(); 
}

Summary

That’s a brief about C# 6.0 new features. I will keep on adding details and other features.

Article tagged as
Author
Author: Ashish Shukla
Published On: 20/09/2015
Last revised On: 14/11/2015
View all articles by Ashish Shukla

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media