In this article, we will learn top 10 new features of C# 6.0.

1. Static Using Syntax:

Before C# 6.0, In a console application if you wanted to print something, then you would write the following line of code:



using System; namespace CSharpStar { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } 1 2 3 4 5 6 7 8 9 10 11 using System ; namespace CSharpStar { class Program { static void Main ( string [ ] args ) { Console . WriteLine ( "Hello World!" ) ; } } }



In C# 6, you can now add the using static qualifier and reference the WriteLine method by itself as shown below:



using static System.Console; namespace CsharpStar { class Program { static void Main(string[] args) { WriteLine("Hello World!"); } } } 1 2 3 4 5 6 7 8 9 10 11 using static System . Console ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { WriteLine ( "Hello World!" ) ; } } }



This will also work for custom classes created by yourself. Let’s look at the below example.



using static System.Console; using static CsharpStar.CustomClass; namespace CsharpStar { class Program { static void Main(string[] args) { WriteLine("Hello World!"); HelloCshrpStar(); } } static class CustomClass { public static void HelloCshrpStar() { WriteLine("Hello CsharpStar!"); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 using static System . Console ; using static CsharpStar . CustomClass ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { WriteLine ( "Hello World!" ) ; HelloCshrpStar ( ) ; } } static class CustomClass { public static void HelloCshrpStar ( ) { WriteLine ( "Hello CsharpStar!" ) ; } } }



Since you have declared CustomClass with the static keyword, you can run the method by just calling the method name. The output for this sample program would be :



Hello World! Hello CsharpStar! 1 2 Hello World ! Hello CsharpStar !

2. String Interpolation :

String Interpolation is a mechanism to concatenate two or more strings together.In older versions of C#, we were using “+” operator or String.Format method to concatenate strings but in C# 6.0, Microsoft has provided a feature named String Interpolation to concatenate strings.



Using “+” Operator:

class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public int age{ get; set; } static void Main(string[] args) { // In Visual Studio 2013 Customer cus = new Customer(); cus.FirstName = "Lana"; cus.LastName = "Leonard"; cus.Email = "Lana.Leonard@Csharpstar.com"; cus.age = 31; Console.WriteLine("Name : "+ cus.FirstName+" " +cus.LastName+"

Email : "+cus.Email); Console.ReadLine(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Customer { public string FirstName { get ; set ; } public string LastName { get ; set ; } public string Email { get ; set ; } public int age { get ; set ; } static void Main ( string [ ] args ) { // In Visual Studio 2013 Customer cus = new Customer ( ) ; cus . FirstName = "Lana" ; cus . LastName = "Leonard" ; cus . Email = [email protected]" ; cus . age = 31 ; Console . WriteLine ( "Name : " + cus . FirstName + " " + cus . LastName + "

Email : " + cus . Email ) ; Console . ReadLine ( ) ; } }

Using String.Format method:

class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public int age{ get; set; } static void Main(string[] args) { // In Visual Studio 2013 Customer cus = new Customer(); cus.FirstName = "Lana"; cus.LastName = "Leonard"; cus.Email = "Lana.Leonard@Csharpstar.com"; cus.age = 31; Console.WriteLine(string.Format("Name : {0} {1}

Email : {2}", cus.FirstName, cus.LastName, cus.Email)); Console.ReadLine(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Customer { public string FirstName { get ; set ; } public string LastName { get ; set ; } public string Email { get ; set ; } public int age { get ; set ; } static void Main ( string [ ] args ) { // In Visual Studio 2013 Customer cus = new Customer ( ) ; cus . FirstName = "Lana" ; cus . LastName = "Leonard" ; cus . Email = [email protected]" ; cus . age = 31 ; Console . WriteLine ( string . Format ( "Name : {0} {1}

Email : {2}" , cus . FirstName , cus . LastName , cus . Email ) ) ; Console . ReadLine ( ) ; } }

New ways of String Concatenation in C#6.0

using static System.Console; namespace CSharpStar { class Program { static void Main(string[] args) { string firstName = "Lana"; string lastName = "Leonard"; WriteLine($"{firstName} {lastName} is my name!"); ReadLine(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 using static System . Console ; namespace CSharpStar { class Program { static void Main ( string [ ] args ) { string firstName = "Lana" ; string lastName = "Leonard" ; WriteLine ( $ "{firstName} {lastName} is my name!" ) ; ReadLine ( ) ; } } }



The output for this program will be:

Lana Leonard is my name! 1 Lana Leonard is my name !

3. Exception Filters:

Earlier Exception filters were supported in Visual Basic but not in C#. They allow you to specify a condition for a catch block.



using System; using static System.Console; namespace CSharpStar { class Program { static void Main(string[] args) { var httpStatusCode = 404; Write("HTTP Error: "); try { throw new Exception(httpStatusCode.ToString()); } catch (Exception ex) { if (ex.Message.Equals("500")) Write("Bad Request"); else if (ex.Message.Equals("401")) Write("Unauthorized"); else if (ex.Message.Equals("402")) Write("Exception Occurred"); else if (ex.Message.Equals("403")) Write("Forbidden"); else if (ex.Message.Equals("404")) Write("Not Found"); } ReadLine(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 using System ; using static System . Console ; namespace CSharpStar { class Program { static void Main ( string [ ] args ) { var httpStatusCode = 404 ; Write ( "HTTP Error: " ) ; try { throw new Exception ( httpStatusCode . ToString ( ) ) ; } catch ( Exception ex ) { if ( ex . Message . Equals ( "500" ) ) Write ( "Bad Request" ) ; else if ( ex . Message . Equals ( "401" ) ) Write ( "Unauthorized" ) ; else if ( ex . Message . Equals ( "402" ) ) Write ( "Exception Occurred" ) ; else if ( ex . Message . Equals ( "403" ) ) Write ( "Forbidden" ) ; else if ( ex . Message . Equals ( "404" ) ) Write ( "Not Found" ) ; } ReadLine ( ) ; } } }

In C#6.0, without entering the catch block, you can check to see which condition met your exception.

using System; using static System.Console; namespace CsharpStar { class Program { static void Main(string[] args) { var httpStatusCode = 404; Write("HTTP Error: "); try { throw new Exception(httpStatusCode.ToString()); } catch (Exception ex) when (ex.Message.Equals("400")) { Write("Bad Request"); ReadLine(); } catch (Exception ex) when (ex.Message.Equals("401")) { Write("Unauthorized"); ReadLine(); } catch (Exception ex) when (ex.Message.Equals("402")) { Write("Exception Occurred "); ReadLine(); } catch (Exception ex) when (ex.Message.Equals("403")) { Write("Forbidden"); ReadLine(); } catch (Exception ex) when (ex.Message.Equals("404")) { Write("Not Found"); ReadLine(); } ReadLine(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 using System ; using static System . Console ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { var httpStatusCode = 404 ; Write ( "HTTP Error: " ) ; try { throw new Exception ( httpStatusCode . ToString ( ) ) ; } catch ( Exception ex ) when ( ex . Message . Equals ( "400" ) ) { Write ( "Bad Request" ) ; ReadLine ( ) ; } catch ( Exception ex ) when ( ex . Message . Equals ( "401" ) ) { Write ( "Unauthorized" ) ; ReadLine ( ) ; } catch ( Exception ex ) when ( ex . Message . Equals ( "402" ) ) { Write ( "Exception Occurred " ) ; ReadLine ( ) ; } catch ( Exception ex ) when ( ex . Message . Equals ( "403" ) ) { Write ( "Forbidden" ) ; ReadLine ( ) ; } catch ( Exception ex ) when ( ex . Message . Equals ( "404" ) ) { Write ( "Not Found" ) ; ReadLine ( ) ; } ReadLine ( ) ; } } }

4. Await in a Catch and Finally Block:

In C# 6, now you can write asynchronous code inside a catch/finally block. This will help you to log exceptions to a file or database without blocking the current thread. Let’s look at below example:

using System; using System.Net.Http; using System.Threading.Tasks; using static System.Console; namespace CSharpStar { class Program { static void Main(string[] args) { Task.Factory.StartNew(() => GetSite()); ReadLine(); } private async static Task GetSite() { HttpClient client = new HttpClient(); try { var result = await client.GetStringAsync ("http://www.CsharpStar.com"); WriteLine(result); } catch (Exception exception) { try { //This asynchronous request will invoked // if the first request is failed. var result = await client.GetStringAsync ("http://www.easywcf.com"); WriteLine(result); } catch { WriteLine("Entered Catch Block"); } finally { WriteLine("Entered Finally Block"); } } } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 using System ; using System . Net . Http ; using System . Threading . Tasks ; using static System . Console ; namespace CSharpStar { class Program { static void Main ( string [ ] args ) { Task . Factory . StartNew ( ( ) = > GetSite ( ) ) ; ReadLine ( ) ; } private async static Task GetSite ( ) { HttpClient client = new HttpClient ( ) ; try { var result = await client . GetStringAsync ( "http://www.CsharpStar.com" ) ; WriteLine ( result ) ; } catch ( Exception exception ) { try { //This asynchronous request will invoked // if the first request is failed. var result = await client . GetStringAsync ( "http://www.easywcf.com" ) ; WriteLine ( result ) ; } catch { WriteLine ( "Entered Catch Block" ) ; } finally { WriteLine ( "Entered Finally Block" ) ; } } } } }

5. Null Conditional Operator:

Most of us do not like NullReferenceException . Let’s look at below example, on how to handle NullReferenceException prior to C#6.0.

using System; using static System.Console; namespace CsharpStar { class Program { static void Main(string[] args) { Employee Emp = new Employee(); if (Emp.Name == String.Empty) { Emp = null; } WriteLine(Emp!= null ? Emp.Name : "Field is null."); ReadLine(); } } public class Employee { public string Name { get; set; } = ""; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 using System ; using static System . Console ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { Employee Emp = new Employee ( ) ; if ( Emp . Name == String . Empty ) { Emp = null ; } WriteLine ( Emp != null ? Emp . Name : "Field is null." ) ; ReadLine ( ) ; } } public class Employee { public string Name { get ; set ; } = "" ; } }



If you enter some data into name, then the console prints out that name else this returns “Field is null”.

New ways to handle NullReferenceException in C#6.0:

In C# 6.0, you can use ?. to check if an instance is null or not. Let’s look at below example to see how it works in C#6.0.



using System; using static System.Console; namespace CsharpStar { class Program { static void Main(string[] args) { Employee Emp = new Employee(); if (Emp.Name == String.Empty) { Emp = null; } WriteLine(Emp?.Name ?? "Field is null."); ReadLine(); } } public class Employee { public string Name { get; set; } = ""; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 using System ; using static System . Console ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { Employee Emp = new Employee ( ) ; if ( Emp . Name == String . Empty ) { Emp = null ; } WriteLine ( Emp ? . Name ? ? "Field is null." ) ; ReadLine ( ) ; } } public class Employee { public string Name { get ; set ; } = "" ; } }

6. Auto Property Initializer:

Prior to C#6.0, we were using constructor to initialize the auto properties to non-default value.

using System; namespace CsharpStar { class Program { static void Main(string[] args) { Employee Emp = new Employee(); Console.WriteLine(Emp. EmployeeID); Console.ReadLine(); } } public class Employee { public Employee() { Employee ID = Guid.NewGuid(); } public Guid EmployeeID{ get; set; } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { Employee Emp = new Employee ( ) ; Console . WriteLine ( Emp . EmployeeID ) ; Console . ReadLine ( ) ; } } public class Employee { public Employee ( ) { Employee ID = Guid . NewGuid ( ) ; } public Guid EmployeeID { get ; set ; } } }

In C#6.0, you can modify the Employee class and populate the property called EmployeeID with inline initialization.

using System; using static System.Console; namespace CsharpStar { class Program { static void Main(string[] args) { Employee Emp = new Employee(); WriteLine(Emp.EmployeeID); ReadLine(); } } public class Employee { public Guid EmployeeID { get; set; } = Guid.NewGuid(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 using System ; using static System . Console ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { Employee Emp = new Employee ( ) ; WriteLine ( Emp . EmployeeID ) ; ReadLine ( ) ; } } public class Employee { public Guid EmployeeID { get ; set ; } = Guid . NewGuid ( ) ; } }

The output for this sample will be a random guid generated by the system.



7. Dictionary Initializers:

In C# 5, you would initialize the Dictionary with a {“Key”, “Value”} Pair. Let’s look at below example to understand it better.

using System.Collections.Generic; namespace CsharpStar { class Program { static void Main(string[] args) { var Books = new Dictionary<int, string> () { { 1, "ASP.net" }, { 2, "C#" }, { 3, "ASP.net MVC5" } }; foreach (KeyValuePair<int, string> keyValuePair in Books) { Console.WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "

"); } Console.ReadLine(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 using System . Collections . Generic ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { var Books = new Dictionary < int , string > ( ) { { 1 , "ASP.net" } , { 2 , "C#" } , { 3 , "ASP.net MVC5" } } ; foreach ( KeyValuePair < int , string > keyValuePair in Books ) { Console . WriteLine ( keyValuePair . Key + ": " + keyValuePair . Value + "

" ) ; } Console . ReadLine ( ) ; } } }

In C# 6, you can place the key between two square brackets [“Key”] and then set the value of the key [“Key”] = “value”.

using System.Collections.Generic; using static System.Console; namespace Csharpstar { class Program { static void Main(string[] args) { var Books = new Dictionary<int, string> () { [1] = "ASP.net", [2] = "C#", [3] = "ASP.net MVC5" }; foreach (KeyValuePair<int, string> keyValuePair in Books) { WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "

"); } ReadLine(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 using System . Collections . Generic ; using static System . Console ; namespace Csharpstar { class Program { static void Main ( string [ ] args ) { var Books = new Dictionary < int , string > ( ) { [ 1 ] = "ASP.net" , [ 2 ] = "C#" , [ 3 ] = "ASP.net MVC5" } ; foreach ( KeyValuePair < int , string > keyValuePair in Books ) { WriteLine ( keyValuePair . Key + ": " + keyValuePair . Value + "

" ) ; } ReadLine ( ) ; } } }

8.Expression Bodied Function & Property:

Expression Bodied Functions are functions with no statement body. Instead, you implement them with an expression following the function declaration

using static System.Console; namespace CsharpStar { class Program { private static double AddNumbers (double num1, double num2) => num1 + num2; static void Main(string[] args) { double num1 = 3; double num2 = 7; WriteLine(AddNumbers(num1, num2)); ReadLine(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 using static System . Console ; namespace CsharpStar { class Program { private static double AddNumbers ( double num1 , double num2 ) = > num1 + num2 ; static void Main ( string [ ] args ) { double num1 = 3 ; double num2 = 7 ; WriteLine ( AddNumbers ( num1 , num2 ) ) ; ReadLine ( ) ; } } }

The result of the above program would be 10.

9. Getter-only Auto Properties:

When you use auto implemented properties in C# 5 and lower, you must provide a get and set. If you want the property value to be immutable, you can use the private accessor on the setter. With C# 6, you can now omit the set accessor to achieve true readonly auto implemented properties:



public DateTime BirthDate { get; } 1 public DateTime BirthDate { get ; }

10. NameOf Expression:

Name of Expression is a new feature introduced in C#6.0.In Enterprise level applications, we handle exceptions at different levels.Showing a specific type name with an error message can be an easy way to find the code block where the exception just occurred. But by adding this we can’t show it to user because the type name can be changed anytime while refactoring but hard coded string won’t change accordingly.



Before C# 6.0 :

using System; using static System.Console; namespace CsharpStar { class Program { static void Main(string[] args) { DoWork("Hello World!!"); ReadLine(); } public static void DoWork (string Title) { if (Title == null) throw new Exception("Title is null"); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 using System ; using static System . Console ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { DoWork ( "Hello World!!" ) ; ReadLine ( ) ; } public static void DoWork ( string Title ) { if ( Title == null ) throw new Exception ( "Title is null" ) ; } } }

What happens if someone changes the Title variable to newTitle? Since we hard-coded the “Title is null” error, that is what will appear to the end-user. We would rather it now say, “newTitle is null”, but the compiler cannot recognize this.

In C# 6.0, we can refactor our code to remove the string literals and use the nameof expression.

using System; using static System.Console; namespace CsharpStar { class Program { static void Main(string[] args) { DoWork("Hello World!!"); ReadLine(); } public static void DoWork(string newTitle) { if (newTitle == null) throw new Exception(nameof(newTitle) + " is null"); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 using System ; using static System . Console ; namespace CsharpStar { class Program { static void Main ( string [ ] args ) { DoWork ( "Hello World!!" ) ; ReadLine ( ) ; } public static void DoWork ( string newTitle ) { if ( newTitle == null ) throw new Exception ( nameof ( newTitle ) + " is null" ) ; } } }

Summary:

In this article, we have discussed top 10 new features introduced in C# 6.0.

– Auto Property Initializer

– Await in a Catch and Finally Block in C#6.0

– Dictionary Initializers in C# 6.0

– Exception Filters in C#6.0

– Expression Bodied Function & Property in C#6.0

– Getter-only Auto Properties in C#6.0

– NameOf Expression in C#6.0

– Null Conditional Operator in C#6.0

– Static Using Syntax in C#6.0

– String Interpolation in C#6.0



Thanks For visiting !!

© 2016, Csharp Star. All rights reserved.