TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

C# 6.0 Features | What is new in C# 6.0

C# 6.0 if the latest version of C# language which ships with Visual Studio 2015. C#.NET 6.0 comes with a set of new advanced features which are mainly targetted to improve the developer experience.

A new compiler technology named "Roslyn" also introduced this time which is an open source under the Apache 2 licence.Roslyn,which is completely developed in C#, will improve compiler efficiency and will make feature integration to languages are very easy.Accordingly in C# version 6.0 Microsoft has added a lot of features that enhance the productivity of both writing and reading C# code. .

Following are the major new features of C# 6.0.

 1)  Null-conditional operators or Null Propagation Operator 

System.NullReferenceException or "Object reference not set to an instance of an object" is very common for almost every C# developer.This is because the accessing object is not instantiated and having value null.So we end up using lot of null checks in our code to avoid exception.

In C# 6.0 we can get rid of this null check by using Null Propagation operator like,

string empName = employee?.Name;

Here even if the empoyee instance of Employee class is null you won't get an exception.Instead you will get a null value for the variable empName.

Null-conditional operators are very helpful in removing lot of nested if statements wherein each if statement checks a variable against null.Null Propagation Operators definitely improves the coding speed and code readability.

 

2) Index Initializers | Dictionay Initializers | Indexer Initializer 

C# 6 offers an alternative syntax for initializing dictionay.We have already collection initializer which can be used for dictionay initialization also.There is no major change syntax wise.Internally Collection Initializer syntax for dictionay initialization is translated into dictionary.Add() calls, while the new Index Initializers are translated into index assignments.Example Index Initializer is,

var dictionary =

    new Dictionary<string, string>

    {

        ["001"] = "John",

        ["002"] = "Peter",

        ["003"] = "Mary"

    };

 

3) Event initializers

 

4) Nameof expressions 

 

5) Extension Add methods 

 

6) String interpolation

String interpolation allows you put the expressions right in their place. String.Format uses {X} as placeholders in the format string, which lines up with arguments supplied separately like,

var str = String.Format("{0} is a {1}} old", emp.Name, emp.Desig);

This can be replaced in C# 6.0 as  

var str = "\{emp.Name} is a \{emp.Desig}";

 

7) Auto-property initializers 

In C# 6.0 we can initialize the properties with default values at the time of defining them.The following is the syntax for initializing properties in C# 6.0 with a default value on both setter and getter.Setter will trigger the propertychanged event. 

public class Employee

{

     public string Name { get; set; } = "Rajeev";

     public string Designation { get; set;} = "Software Engineer";

}

 

8) Getter-only auto-properties 

 The following is the syntax for read only properties:

public class Employee

{

     public string Name { get; } = "Rajeev";

     public string Designation{ get; } = "Software Engineer";

}

 

8) Field targets on auto properties

 

9) Overload resolution

 

10) Exception filters 

Exception Filters filter the catch clause so that specific Catch Block  will only be executed if the condition is true.

For example, 

try 

{ 

   // try block code here.

} 

catch (CustomException ex) if (ex.data > 100)

{

    //Exception handler code here. 

}

Here, Exception block code will be executed only if condition result is true.If false, the exception will be thrown if not handled by some othe following exception blocks.

 

11) Await in catch and finally blocks 

In certain cases,you may want to have the ability to await an asynchronous call inside a catch block or finally block.In earlier versions of C# you won't be able to use await in catch block because it was not supported in C# due to implementation complexity.In C# 6.0,Microsoft implementated this feature and you will be able to await an expression either inside a catch block or inside a finally block.

 

13) Expression-bodied function members 

Expression bodied members allows us to write class members such as methods,property get accessors and get for indexers as simple expressions instead of statement blocks.Lambda expressions can be declared with an expression body as well as a conventional function body consisting of a block.Methods as well as user-defined operators and conversions can be given an expression body by use of the “lambda arrow”:

For example, If we have a Property in a class like the older fashion,

public int Area

{

    get

    {

        return Length * width;

    }

 

} 

With the introduction of Expression bodied members features it is simply as below,

public int Area=> Height * Width;

 

14) Primary Constructors 

Primary Constructors enables us to initialize Properties in a much simpler manner, within in constructor itself.For example, In earlier versions initializing certain Property's are done in the following manner.For example,here below an Employee class first declare the local variables and then get it assigned with value in constructor.Hence the property will get value as soon as the instance is created.

public class Employee

{

     //local variables declared

     private string name;

     private string desig;


     //Overloaded constructor which assigns value to local variables.

     public Employee(string name, string desig)

     {

         this.first = first;

         this.desig = desig;

     }


     //Properties with get access.

     public string Name { get { return name; } }

     public string Designation { get { return desig; } }

}

In C# 6.0 using primary constructor the above stuff will be writtes in simpler maaner as

/

/Primary Constructor implementation C# 6.0

public class Employee(string name,string desig) 

{

     public string Name{ get; } = name;

     public string Designation{ get; } = desig;

}

 

15) Parameterless constructors in structs 

In earlier versions,before 6.0,C# does not allow structs to have a default parameterless constructor since for value type by default compilers never generate a call to the default constructor.Hence the C# compiler doesn't allow definition of a default constructor by the user.If you define a default constructor it will not be called at all.This was a drawback and in C# 6.0 now it is possible to have structs with parameterless constructors.

 

16) using static 

using static feature in C# 6.0, enables us to use static members of the static class withput namespace qualifiers.For example if you have a static Helper class or a static utility class,normally the member functions accessed with qualifier and '.' operator.But now on with C# 6, you can specify static class in a using clause to make all its members accessible in the current context.

using System.Console; //static console class, out of the box

using [FullNameSpce].Helper;  //Static helper class which contains some static helper methods.

class Program

{

 static void Main()

 {

    WriteLine(CalculateArea(int width, int height)); 

 }

}

Here WriteLine is a static method within Console class and CalculateArea is a static helper method within Helper class.They both are used without qualifiers since using clause is given on top.

 

17) Binary literals 

This small additions to the way literals can be used in C#. Now we can have a binary literal like,

int num = 0b0111;

 

18) Digit separators for hexadecimal

On readability point of view,it would be better if there is a provision to seperate digits in Hexadecimal numbers with sepearators.C# 6.0 gives us that provision.Here a hexadecimal number can be written with a '_'seperator.For example,the hexadecimal number 0xFFAABB0C can be represented as 0xFF_AA_BB_0C.With the seperator the hexanumber is better visually.

int num = 0xFF_AA_BB_0C

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading