List of All New Features in C# 6.0: Part 1

Microsoft has announced some new keywords and some new behavior of C# 6.0 in Visual Studio 2015.

visual studio 2015

In this article, we will learn the following topics.

  1. using Static.
  2. Auto property initializer.
  3. Dictionary Initializer.
  4. nameof Expression.
  5. New way for Exception filters.
  6. await in catch and finally block.
  7. Null – Conditional Operator.
  8. Expression – Bodied Methods
  9. Easily format strings – String interpolation

For testing all

Open Visual Studio 2015 and select "File" -> "New" -> "Project...".

console application

Click OK and then you will get a solution that you will see in the Solution Explorer.

progarm

Now just do something with your program.cs file to test your compile time code.

1. using Static


This is a new concept in C# 6.0 that allows us to use any class that is static as a namespace that is very useful for every developer in that code file where we need to call the static methods from a static class like in a number of times we need to call many methods from Convert.ToInt32() or Console.Write(),Console.WriteLine() so we need to write the class name first then the method name every time in C# 5.0. In C# 6.0 however Microsoft announced a new behavior to our cs compiler that allows me to call all the static methods from the static class without the name of the classes because now we need to first use our static class name in starting with all the namespaces.
    In C# 5.0

    name space


    In C# 6.0


    Code in 5.0

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. namespace TestNewCSharp6  
    7. {  
    8.     class Program  
    9.     {  
    10.         static void Main(string[] args)  
    11.         {  
    12.             Console.WriteLine("Enter first value ");  
    13.             int val1 =Convert.ToInt32(Console.ReadLine());  
    14.             Console.WriteLine("Enter next value ");  
    15.             int val2 = Convert.ToInt32(Console.ReadLine());  
    16.             Console.WriteLine("sum : {0}", (val1 + val2));  
    17.             Console.ReadLine();  
    18.         }  
    19.     }  
    20. }  
    Code in C# 6.0
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using static System.Convert;  
    7. using static System.Console;  
    8. namespace Project1  
    9. {  
    10.     class Program  
    11.     {  
    12.         static void Main(string[] args)  
    13.         {  
    14.             WriteLine("Enter first value ");  
    15.             int val1 = ToInt32(ReadLine());  
    16.             WriteLine("Enter next value ");  
    17.             int val2 = ToInt32(ReadLine());  
    18.             WriteLine("sum : {0}", (val1+val2));  
    19.             ReadLine();  
    20.         }  
    21.     }  
    22. }  
    Now you can see the difference for yourself, there is less code but the output will be the same.

    Output

    Output 

2. Auto property initializer


Auto property initializer is a new concept to set the value of a property during of property declaration. We can set the default value of a read=only property, it means a property that only has a {get;} attribute. In the previous version of C# 5.0 we can set the values of the property in the default constructor of the class. Let's have an example. Suppose we need to set some property's value of a class as in the following:

    In C# 5.0

    class

    Code

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. namespace TestNewCSharp6  
    6. {  
    7.     class Emp  
    8.     {  
    9.         public Emp()  
    10.         {  
    11.             Name = "nitin";  
    12.             Age = 25;  
    13.             Salary = 999;  
    14.         }  
    15.         public string Name { getset; }  
    16.         public int Age { getset; }  
    17.         public int Salary { get;private set; }  
    18.     }  
    19. }  
    Here we can set the default value of my property in only by constructors.

    In C# 6.0

    class emp

    Code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6.   
    7. namespace Project2  
    8. {  
    9.     class Emp  
    10.     {  
    11.         public string Name { getset; }="nitin";  
    12.         public int Age { getset; }=25;  
    13.         public int Salary { get; }=999;  
    14.     }  
    15. }  
    Here we can initialization the default value for the property in the same line. 

3. Dictionary Initializer


Dictionary initializer is a new concept in C# 6.0. We can directly initialize a value of a key in a Dictionary Collection with it, either the key in the collection would be a string data type or any other data type. Let's see the declaration syntax in both versions like in C# 5.0 and also in C# 6.0 respectively.
    C# 5.0

    cs code


    Code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Linq;  
    5. using System.Text;  
    6. using System.Threading.Tasks;  
    7. namespace TestNewCSharp6  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main(string[] args)  
    12.         {  
    13.             Dictionary<stringstring> dicStr = new Dictionary<stringstring>()  
    14.             {  
    15.                 {"Nitin","Noida"},  
    16.                 {"Sonu","Baraut"},  
    17.                 {"Rahul","Delhi"},  
    18.             };  
    19.             dicStr["Mohan"] = "Noida";  
    20.             foreach (var item in dicStr)  
    21.             {  
    22.                 Console.WriteLine(item.Key+"   "+ item.Value);  
    23.             }  
    24.             Console.WriteLine("********************************************************************");  
    25.             Dictionary<intstring> dicInt = new Dictionary<intstring>()  
    26.             {  
    27.               {1,"Nitin"},  
    28.               {2,"Sonu"},  
    29.               {3,"Mohan"},  
    30.             };  
    31.             dicInt[4] = "Rahul";  
    32.             foreach (var item in dicInt)  
    33.             {  
    34.                 Console.WriteLine(item.Key + "   " + item.Value);  
    35.             }  
    36.             Console.Read();  
    37.         }  
    38.     }  
    39. }  
    C# 6.0

    Dictionary Initializer


    Code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Linq;  
    5. using System.Text;  
    6. using System.Threading.Tasks;  
    7. namespace Project3  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main(string[] args)  
    12.         {  
    13.             Dictionary<stringstring> dicStr = new Dictionary<stringstring>()  
    14.             {  
    15.                 ["Nitin"]="Noida",  
    16.                 ["Sonu"]="Baraut",  
    17.                 ["Rahul"]="Delhi",  
    18.             };  
    19.             dicStr["Mohan"] = "Noida";  
    20.             foreach (var item in dicStr)  
    21.             {  
    22.                 Console.WriteLine(item.Key + "   " + item.Value);  
    23.             }  
    24.             Console.WriteLine("********************************************************************");  
    25.             Dictionary<intstring> dicInt = new Dictionary<intstring>()  
    26.             {  
    27.               [1]="Nitin",  
    28.               [2]="Sonu",  
    29.               [3]="Mohan"  
    30.             };  
    31.             dicInt[4] = "Rahul";  
    32.             foreach (var item in dicInt)  
    33.             {  
    34.                 Console.WriteLine(item.Key + "   " + item.Value);  
    35.             }  
    36.             Console.Read();  
    37.         }  
    38.     }  
    39. }  
    Here we can initialize the Dictionary values directly by the “=” operator and in C# 5.0 we need to create an object as a {key,value} pair and the output will be the same in both versions.

    Output

    program Output

4. nameof Expression


nameof is new keyword in C# 6.0 and it's very useful from a developer's point of view because when we need to use a property, function or a data member name into a message as a string so we need to use the name as hard-coded in “name” in the string and in the future my property or method's name will be changed so it must change all the messages in every form or every page so it's very complicated to remember that how many number of times you already use the name of them in your project code files and this avoids having hardcoded strings to be specified in our code as well as avoids explicit use of reflection to get the names. Let's have an example.

    We have a class:

    class employee

    And we need to show the values of this class property to the console and also if we need to print the name of my property too with the message so in C# 6.0 we can use the nameof expression rather than hardcode the name of the property.

    nameof

    Output

    nameof output


    Code

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using System.Console;  
    7. namespace Project4  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main(string[] args)  
    12.         {  
    13.             Employee emp = new Employee();  
    14.             WriteLine("{0} : {1}", nameof(Employee.Id), emp.Id);  
    15.             WriteLine("{0} : {1}", nameof(Employee.Name), emp.Name);  
    16.             WriteLine("{0} : {1}", nameof(Employee.Salary), emp.Salary);  
    17.             ReadLine();  
    18.         }  
    19.     }  
    20.     class Employee  
    21.     {  
    22.         public int Id { getset; } = 101;  
    23.         public string Name { getset; } = "Nitin";  
    24.         public int Salary { getset; } = 9999;  
    25.     }  
    26. }   

5. Exception filters


Exception filters are a new concept for C#. In C# 6.0 they are already supported by the VB compiler but now they are coming into C#. Exception filters allow us to specify a condition with a catch block so if the condition will return true then the catch block is executed only if the condition is satisfied. This is also the best attribute of new C# 6.0 that makes it easy to do exception filtrations in also that type of code contains a large amount of source code. Let's have an example.
    if condiction

    Code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using System.Console;  
    7. namespace project5  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main(string[] args)  
    12.         {  
    13.             int val1 = 0;  
    14.             int val2 = 0;  
    15.             try  
    16.             {  
    17.                 WriteLine("Enter first value :");  
    18.                 val1 = int.Parse(ReadLine());  
    19.                 WriteLine("Enter Next value :");  
    20.                 val2 = int.Parse(ReadLine());  
    21.                 WriteLine("Div : {0}", (val1 / val2));  
    22.             }  
    23.             catch (Exception ex) if (val2 == 0)  
    24.             {  
    25.                 WriteLine("Can't be Division by zero ☺");  
    26.             }  
    27.             catch (Exception ex)  
    28.             {  
    29.                 WriteLine(ex.Message);  
    30.             }  
    31.             ReadLine();  
    32.         }  
    33.     }  
    34. }  
    Output

    If all the values are entered by user id correctly then the output will be:

    user id correct

    If the user enters an invalid value for division, like 0, then it will throw the exception that will be handled by Exception filtration where you mentioned an if() with catch{} block and the output will be something.

6. Await in catch and finally block


This is a new behavior of C# 6.0 that now we are able to call async methods from catch and also from finally. Using async methods are very useful because we can call then asynchronously and while working with async and await, you may have experienced that you want to put some of the result awaiting either in a catch or finally block or in both. Let's suppose we need to call an async method and there is a try and a catch{} block so when the exception occurs it is thrown in the catch{} block. We need to write log information into a file or send a service call to send exception details to the server so call the asynchronous method, so use await in catch{}, this is only possible in C# 6.0. Let's have an example.

We have a class and there is a method that is async and we need to call this with two parameters and if there is an exception then that will we return an exception and will go to the catch{} block and then we will call an async method using await and finally we have called the same in the finally.
    Await in catch and finally block

    Call the async div() in Main().

    async

    Code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using System.Console;  
    7. namespace project6  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main(string[] args)  
    12.         {  
    13.             MyMath obj = new MyMath();  
    14.             obj.Div(12, 0);  
    15.             ReadLine();  
    16.         }  
    17.     }  
    18.     public class MyMath  
    19.     {  
    20.         public async void Div(int value1, int value2)  
    21.         {  
    22.             try  
    23.             {  
    24.                 int res = value1 / value2;  
    25.                 WriteLine("Div : {0}", res);  
    26.             }  
    27.             catch (Exception ex)  
    28.             {  
    29.                 await asyncMethodForCatch();  
    30.             }  
    31.             finally  
    32.             {  
    33.                 await asyncMethodForFinally();  
    34.             }  
    35.         }  
    36.         private async Task asyncMethodForFinally()  
    37.         {  
    38.             WriteLine("Method from async finally Method !!");  
    39.         }  
    40.   
    41.         private async Task asyncMethodForCatch()  
    42.         {  
    43.             WriteLine("Method from async Catch Method !!");  
    44.         }  
    45.     }  
    46. }  
    Output

    If there is no exception then:

    any exception then

    And when the exception occurs:

    at the time of exception

7. Null-Conditional Operator


The Null-Conditional operator is a new concept in C# 6.0 that is very beneficial for a developer in a source code file that we want to compare an object or a reference data type with null. So we need to write multiple lines of code to compare the objects in previous versions of C# 5.0 but in C# 6.0 we can write an in-line null-conditional with the ? and ?? operators, so let's have an example and compare both versions, C# 5.0 vs C# 6.0. We will write the code for both version. 

    Let's suppose we have two classes:

    Conditional Operator

    Now we need to write the code to compare the objects of the employee class with null in C# 5.0. So we need to write if() and else multiple lines.

    code for compare

    If we want to write the same code in C# 6.0 then we can use ? and ?? to check the null value of an object, as in the following:

    Condition ? code that use in case not null ?? in case of null

    case of null

    Output

    The output when no object is null:

    Output when no object is null

    The output when an object is null:

    When object is null

    Code

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using System.Console;  
    7. namespace project7  
    8. {  
    9.     class Program  
    10.     {  
    11.        static void Main()  
    12.         {  
    13.             Employee emp = new Employee();  
    14.             emp.Name = "Nitin Pandit";  
    15.             emp.EmployeeAddress = new Address()  
    16.             {  
    17.                 HomeAddress = "Noida Sec 15",  
    18.                 OfficeAddress = "Noida Sec 16"  
    19.             };  
    20.             WriteLine((emp?.Name) + "  " + (emp?.EmployeeAddress?.HomeAddress??"No Address"));  
    21.             ReadLine();  
    22.         }  
    23.     }  
    24.     class Employee  
    25.     {  
    26.         public string Name { getset; }  
    27.         public Address EmployeeAddress { getset; }  
    28.     }  
    29.     class Address  
    30.     {  
    31.         public string HomeAddress { getset; }  
    32.         public string OfficeAddress { getset; }  
    33.     }  
    34. }   

8. Expression–Bodied Methods


An Expression–Bodied Method is a very useful way to write a function in a new way and also very useful for those methods that can return their value by a single line so we can write those methods by using the “=>“ lamda Operator in C# 6.0 so let's have an example.

We will just write a method in both versions of C# 5.0 vs C# 6.0 with a method that only returns a message of a string value.
    In C# 5.0:

    gettime


    In C# 6.0

    using for value


    Output

    The output will be the same in both.

    Output will be the same in both

    Code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using System.Console;  
    7. namespace Project8  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main(string[] args)  
    12.         {  
    13.             WriteLine(GetTime());  
    14.             ReadLine();  
    15.         }  
    16.         public static string GetTime()=> "Current Time - " + DateTime.Now.ToString("hh:mm:ss");  
    17.          
    18.     }  
    19. }  

9. Easily format strings using String interpolation


To easily format a string value in C# 6.0 without any string.Format() method we can write a format for a string. It's a very useful and time consuming process to define multiple string values by “\{ variable }”. So let's have an example on String interpolation. First we are writing the source code by string.Format().

    string output

    Now by “\{variable}”.

    variable

    Output

    The output will be the same in both but by “\{variable}” is a very short way to write the same code.

    Output both

    Code

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using System.Console;  
    7. namespace Project9  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main()  
    12.         {  
    13.             string FirstName = "Nitin";  
    14.             string LastName = "Pandit";  
    15.   
    16.             // With String Interpolation in C# 6.0  
    17.             string  output= "\{FirstName}-\{LastName}";  
    18.             WriteLine(output);  
    19.             ReadLine();  
    20.         }  
    21.     }  
    22. }   
Thank you for reading this article.

Next article - List of All New Features in C# 6.0: Part 2


Recommended Free Ebook
Similar Articles