Monday, 30 March 2015

New Features in C# 6.0



The most recent version of C# is C# 6.0 which was release with Microsoft Visual Studio 2015 Preview. There are lot of good features in this version. In this article we will discuss all these features.
1. Auto Property Initializer
In C# 6.0, properties can be initialized at the declaration place just like fields. There is no need to write the constructor to give initial value.
Earlier
public class Customer
{
    public Customer()
    {
        ID = 1;
        FirstName = "Ravi";
        LastName = "Gupta";
    }
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now
public class Customer()
{
    public int ID { get; } = 1;
    public string FirstName { get; } = "Ravi";
    public string LastName { get; } = "Gupta";
}
These initialization doses not cause the setter function to be invoked internally. The value of backing field is set directly.


2. Primary Constructor
Constructor is mainly used to initialize the values of class properties. This is done accepting parameter value and assigned those values in properties.
In C# 6.0, primary constructor provides us shortcut syntax for defining constructor with parameters. Auto-property initializers are especially useful in combination with primary constructors. Parameter Initialization is moved beside the class name.
Earlier
public class Customer
{
    public Customer(int id, string firstName, string lastName)
    {
        ID = id;
        FirstName = firstName;
        LastName = lastName;
    }
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now
public class Customer(int id, string firstName, string lastName)
{
    public int ID { get; } = id;
    public string FirstName { get; } = firstName;
    public string LastName { get; } = lastName;
}
Only one primary constructor is allowed in a class.


3. Exception Filters
Exception filters provide us a feature to check, if condition before the catch block excutes. The catch block gets executed only if the condition is satisfied.
Earlier
try
{
    //Some code
}
catch (Exception ex)
{
    if(ex.InnerException != null)
    {
        //Do work;
    }
}

Now
try
{
    //Some code
}
catch (Exception ex) if (ex.InnerException == null)
{
    //Do work;
}


4. await in catch and finally block
Earlier await keyword was not available inside the catch and finally block. In C# 6, we can use the await keyword inside catch and finally blocks.
try
{                  
    //Do something
}
catch (Exception)
{
    await Logger.Error("exception logging")
}


5. Dictionary Initializer
Dictionary initialization has been made cleaner in C# 6.0.
Earlier
Dictionary<string, string> oldWay = new Dictionary<string, string>()
{
    { "FirstName", "Ravi" },
    { "LastName", "Gupta" },
};

Now
Dictionary<string, string> oldWay = new Dictionary<string, string>()
{
    ["FirstName"] = "Ravi",
    ["LastName"] = "Gupta"
};


6. Using Statics
For invoking a static method you don’t need an instance of object to invoke a method. You invoke it as follow:
ClassName.MethodName

Earlier
public class Test
{
    public void TestMethod()
    {
        Console.WriteLine("Static Using Before C# 6");
    }
}

Now
using System.Console;
namespace newfeatureincsharp6
{
    public class Test
    {
        public void TestMethod()
        {
            WriteLine("Static Using Before C# 6");
        }
    }
}
In C# 6 you have the ability to use the Static Members without using the type name. You can import the static classes in the namespaces.


7. Declaration expressions
Declaration expressions provide a feature to declare local variable in the middle of an expression.
Earlier
long id;
if (!long.TryParse(Request.QureyString["Id"], out id))
{ }

Now
if (!long.TryParse(Request.QureyString["Id"], out long id))
{ }


8. Conditional Access Operator to check NULL Values
Let's have an example:
We have a Customer class with FirstName property. Now we need to set value of FirstName property in a variable and while reading value from this property we need to check null value in Customer class. If it is null then we should get null value in our variable. We will write this code like this:
string firstName;
if(objCustomer != null)
{
    firstName = objCustomer.FirstName;
}
else
{
    firstName = null;
}
or
string firstName = (objCustomer != null) ? objCustomer.FirstName : null;
In C# 6.0, we can check null value easily by conditional access operator:
string firstName = objCustomer?.FirstName
This code will set null in firstName is object of Customer class is null.


9. $ sign
$ sign provides feature to simplify string based indexing. It internally uses regular indexing functionality.
var test = new Dictionary<string, string>()
{
    // using inside the intializer
    $first = "Ravi"
};

//Assign value to member
//the old way:
test["first"] = "Ravi";
  
// the new way  
test.$first = "Ravi";


10. String interpolation
String.Format is used to format strings. But its use is error prone particularly in the use of numbered placeholders like {0} in the format string.
var s = String.Format("{0} is {1} year{{s}} old", p.Name, p.Age);
We have to remember that which placeholder will contain which value and it is a problem if we have many placeholders in single statement. This issue is solved in C# 6.0.
var s = "\{p.Name} is \{p.Age} year{s} old"
String interpolation lets you put the expressions right in their place.



No comments:

Post a Comment