September 15, 2014

C# 6 Language Enhancements

Here I'd like to discuss some new features in C# 6, the upcomming version of C# that will ship with next version of Visual studio. The initial buzz about the next version of C# is that C# compiler complete rewrite, written in C# from ground up. C# 6 gives you a lot of features that enhance your productivity both writing and reading C# code.

1. PRIMARY CONSTRUCTORS:


C# 6 introduces the "Primary Constructor" concept, a way to express an initializing constructor in more concise syntax. 

===========
NEW WAY:
===========

public class Person(string first, string last) 
{
     public string First { get; } = first;
     public string Last { get; } = last;
}

===============
CURRENT WAY:
===============

public class Person
{
     private string first;
     private string last;

     public Person(string first, string last)
     {
         this.first = first;
         this.last = last;
     }

     public string First { get { return first; } }
     public string Last { get { return last; } }
}

2. AUTO PROPERTY INITIALIZERS:


Another good feature C# 6 introduce is "Auto Property Initializer", syntax for initializing properties to set constant values on any property.

=========
NEW WAY:
=========

public class Person
{
     public string First { get; set; } = "Jane";
     public string Last { get; set;} = "Doe";

And, it works on read only properties:

public class Person
{
     public string First { get; } = "Jane";
     public string Last { get; } = "Doe";
}

3. MATH CLASS: 


C# 6 introduces the "MATH" class - a single class instead of entire namespace. It’s another small language change that removes some friction in writing and reading code.

using System.Math;

Once you add that, you can reference any members of the System.Math class without any namespace or class qualifer:

var x = Sqrt(3*3 + 4*4);

4. DICTIONARY INITIALIZERS: 


C# 6 introduced a feature called "Lightweight dynamic" the feature that has changed names as it was refined. The concept is grab from JavaScript and JSON language and this feature allow C# to create DTOs (data transfer objects) in much lighter way rather than going through the overhead of creating a strongly typed class that had no behavior.

5. EXCEPTION FILTERS: 


This feature brings C# up to parity with VB.NET. They work as follows:

try 
   // … 
} catch (MyException e) if (myfilter(e)) 
{
    // … 

The catch clause will only be executed if myfilter(e) returns true. Otherwise, any catch clauses that follow are evaluated, or the exception propagates up the call stack.