Monday, April 3, 2017

C# 6.0 Features - Shortens and Simplifies the code

C# 6.0 shipped with .NET 4.6 and Visual Studio 2015. VS 2015 comes with brand new Roslyn compiler. Developers can use these features in older version by up grading the compiler.

C# 6.0 features gives grand welcome to the developers to Shortens and Simplifies existing/new code.

See the following new features with examples

1. Null-Conditional operators


This feature concisely and safely access members of an object while still checking for null with the null conditional operator

Before:


Int? userRole = (EmployeeObject != null) ? EmployeeObject.Role : null ;
string deptName= (EmployeeObject != null && EmployeeObject.DeptObject !=null) ? EmployeeObject.DeptObject.DeptName : “”;

After:


Int? userRole = EmployeeObject?.Role ;
string deptName = EmployeeObject?.DeptObject?.DeptName ?? “” ;

2. Auto-Property Initializers

You can assign value to the auto property initializer just like normal field

Before:
 public class Customer
{
   public string First { get; set; };
   public string Last { get; set; };
   public Customer()
   {
      First=”John”;
      Last=”Papa”;
    }
}
After:
 public class Customer
  {
      public string First { get; set; } = "John";
      public string Last { get; set; } = "Papa";
  }

3. Index Initializers 

This feature makes collection initializers more consistent with [] brackets 

     Before:
var numbers = new Dictionary<int, string> {
     { 303,"redirection" },
     { 404, "page not found" },
     { 500, "server error" }
}

After 
var numbers = new Dictionary<int, string> {
           [303] = "redirection",
           [404] = "page not found",
           [500] = "server error"
}
You can download all the features with examples from the link : Download

Happy Coding :)

1 comment: