C# 6.0 New Features

There are several new features introduced in C# 6.0; here we discuss some of them. 

C# 6.0 Features 

String Interpolation

Static using

Nameof expression

Auto Property Initializer

Dictionary Initializer

Await in Catch/finally

Null conditional operator

Exception filters

Expression Bodied function 

In this article, we discuss each one of the features. Here we are using Microsoft Visual Studio 2015 to test these features. 

String Interpolation: Before C# 6.0 we used to format the strings using string.Format method. In C# 6.0 can simply format the string by using $ and { } symbols as shown below. 

namespace CSharp6._0Features

{

    class Program

    {

        static void Main(string[] args)

        {

            string firstString = "First";

            string secondString = "Second"; 

            string finalString = $"The strings are {firstString} and {secondString}";

            Console.WriteLine(finalString);

            Console.ReadLine();

         }

    }

} 

Execute the code; you get the same output as a string.Format produces. 

For more details on this visit my post, String Interpolation in C# 

Static using:

As we know, we can access any static class members by using ClassName.Variable name. For example, we can access user defined Employee static class method GetSal() by using Employee.GetSal(). With C#6.0 it is much more simplified; you need to mention class name always before the variable. You have to specify the static class name with the help using statement in the header, and all its members can access directly without a class name as shown below. 

Employee.cs:

namespace CSharp6._0Features

{

    public static class Employee

    {

        public static string GetEmployee()

        {

            return "This is from GetEmployee() method of Employee class";

        } 

        public static string GetSal()

        {

            return "This is from GetSal() method of Employee class";

        }

    }

} 

using System;

using static CSharp6._0Features.Employee; 

namespace CSharp6._0Features

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine(GetEmployee());

            Console.WriteLine(GetSal());

            Console.ReadLine();

        }

    }

} 

Output:

NameOf Expression:

In C# 6.0, nameof expression returns string literal of the property or a method. 

using System;

using static CSharp6._0Features.Employee; 

namespace CSharp6._0Features

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine(nameof(GetEmployee));

            Console.WriteLine(nameof(GetSal));

            Console.ReadLine();

        }

    }

} 

Above code outputs the actual method names as below.

Auto Property Initializer:

Before C# 6.0, we used to initialize the properties values either in the class constructor or some methods. C# 6.0 came up with the feature called Auto Property Initializer where we can initialize the properties while defining itself as shown below. 

namespace CSharp6._0Features

{

    public class Employee

    {

        public int EmployeeId { get; set; } = 100;

        public string EmployeeName { get; set; } = "Raj";

        public double EmployeeSal { get; set; } = 3000;

    }

} 

If you try to access the above class properties without passing values, they return whatever the values they initialized while defining. 

Dictionary Initializer:

C# 6.0 providing initializer feature for dictionary also. We can store the values in the dictionary while defining itself as shown below. 

using System.Collections.Generic; 

namespace CSharp6._0Features

{

    class Program

    {

        private static void Main(string[] args)

        {

            Dictionary<string, string> dicExample = new Dictionary<string, string>()

            {

                {"Key1","Vallue1"},

                {"Key2","Vallue2"},

                {"Key3","Vallue3"},

                {"Key4","Vallue4"},

            };

        }

    }

} 

Await in Catch/finally:

By using this features, we can call async methods in catch and finally blocks as shown below. 

using System;

using System.Threading.Tasks;

namespace CSharp6._0Features

{

    class Program

    {

        private static void Main(string[] args)

        {

            AsyncExample obj = new AsyncExample();

            obj.CallAsync();

            Console.ReadLine();

        }       

    } 

    public class AsyncExample

    {

        public async void CallAsync()

        {

            try

            {

                int i1 = 0;

                int i2 = 1000; 

                int result = i2 / i1;

            }

            catch (Exception ex)

            {

                await firstAsyncMethod();

            }

            finally

            {

                await secondAsyncMethod();

            }

            Console.ReadLine();

        } 

        static async Task firstAsyncMethod()

        {

            Console.WriteLine("First Async method");

        } 

        static async Task secondAsyncMethod()

        {

            Console.WriteLine("Second Async method");

        }

    }

} 

Output:

Null conditional operator:

By using this feature, we can remove the conditional statement to check null value while accessing any variables or methods or objects. 

using System;

using static System.Console;

namespace CSharp6._0Features

{

    class Program

    {

        private static void Main(string[] args)

        {

            Employee obj = new Employee();

            WriteLine(obj?.EmployeeName ?? "No Employee names available");

            ReadLine();

        }

    }

} 

Here we are checking whether Employee object is null or not by using ? operator and displaying some value if it is null by using ?? operator. 

Exception filters:

Till C# 5.0, we are using the if condition in the catch block to check for the specific type of exception. However, in C# 6.0, we can add the condition for catch statement itself as shown below. 

using System;

using static System.Console; 

namespace CSharp6._0Features

{

    class Program

    {

        private static void Main(string[] args)

        {

            try

            {

                int n1 = 100;

                int n2 = 0; 

                int result = n1 / n2;

            }

            catch (Exception ex) when (ex.Message.ToLower().Contains("divide by zero"))

            {

                WriteLine(ex.Message);

            }

            Console.ReadLine();

        }

    }

} 

As shown above, we have added the condition for catch block to check whether exception contains divide by zero or not. 

Expression Bodied function and Property:

In C# 6.0, you can compute methods and properties using lambda expressions as below. 

public class Employee

{

        public string FirstName { get; set; } = "Bill";

        public string SecondName { get; set; } = "Gates"; 

        public string FullName => FirstName + " " + SecondName;

        private static int Sum(int n1, int n2) => n1 + n2;

}