C# 6.0 New Features String Interpolation, Await In Catch And Finally Block, Exception Filter And Auto Properties Initializer

To demonstrate the new features in C# 6.0 I have chosen small examples which will help you to understand the C# 6.0 new features easily.

I have tried to make it as simple as I can, with small examples which can be enhanced with complex scenarios as per your requirement.

List of new features in C# 6.0

  1. Manipulating string using string interpolation
  2. Using null conditional operator
  3. Using Await in catch and finally block
  4. Adding Exception Filter
  5. Auto properties initializer
  6. Using getter only auto properties
  7. Converting to expression-bodied function member
  8. Using Static

Let’s start looking at each feature before C# 6.0 and after this version. Here I am going to explain it one by one with examples.

Manipulating string using string interpolation

It can be looked at as an improvement to the String.Format functionality where, instead of the place holders, you can directly mention the string expressions or variables.

  1. Place strings where we need them
  2. Specify a space after/before the string
  3. Use conditions
  1. class Program  
  2.     {  
  3.         public string FirstName { getset; }  
  4.         public string LastName { getset; }  
  5.   
  6.         public string GetFullName(string firstName, string lastName) => firstName + lastName;  
  7.         static async void Main(string[] args)  
  8.         {  
  9.   
  10.             string firstName = "Jignesh";  
  11.             string lastName = "Kumar";  
  12.             Console.WriteLine("Full Name of Employee {0} {1}", firstName, lastName);  
  13.   
  14.             // After C# 6.0 Place holder not reqired. You can write like as below  
  15.   
  16.             Console.WriteLine($"Full Name of Employee {firstName} {lastName}");  
  17.   
  18.             Console.ReadLine();  
  19.         }  
  20.     }  
Using null conditional operator

Most of the time developers get this exception: “object reference not set to an instance of an object”. In C# 6 we can handle this easily using NULL Conditional Operator. So we can handle System.NullReferenceException using this operator. Please have a look at the below code  andyou will easily understand how it will save time.

  1. class Program  
  2.    {  
  3.   
  4.        static async void Main(string[] args)  
  5.        {  
  6.            #region Simple Condition  
  7.   
  8.            var employees = new List<EmployeeDetail>();  

  9.            // old way of doing first check employee object is not null   

  10.            var address = employees != null ? employees[0].address : null;  
  11.   
  12.            // After C# 6.0 check null using ? and assign defaul value if its null   
  13.   
  14.            var addressNew = employees[0]?.address ?? null;  
  15.            #endregion  
  16.  
  17.            #region Nested Condition  
  18.            //If employee is not null and address not null then return city of adress  
  19.            // Before C# 6.0  
  20.            if (employees != null && employees[0] != null)  
  21.            {  
  22.                var city = employees[0].address.city;  
  23.            }  
  24.            var empCity = employees != null ? (employees[0].address != null ? employees[0].address.city : null) : null// old way of doing nested condition   
  25.   
  26.            // After C# 6.0  
  27.            var employeeCity = employees[0]?.address?.city; //new way to check nested condtions  
  28.            #endregion  
  29.   
  30.        }  
  31.    }  
Using Await in catch and finally block

Prior to C# 6.0, it was not possible to call async operations in catch {} and finally {} blocks by specifying the await keyword due to implementation specific issues in the C# compiler. Now you will be able to call the await statements in catch {} and finally {} blocks without writing any complicated code. The compiler will automatically handle it.

Here is a code snippet to show you how easily you can call the await for async operations in catch {} and finally {} blocks. Most of the time, we need this to log exceptions and/or do some final clean-ups of the resources

  1. class Program  
  2. {  
  3.    
  4.     static async void Main(string[] args)  
  5.     {  
  6.         Exception exception = null;  
  7.         try  
  8.         {  
  9.             throw new Exception("Something went wrong");  
  10.         }  
  11.         catch (Exception ex)  
  12.         {  
  13.             exception = ex;  
  14.         }  
  15.         if (exception != null)  
  16.         {  
  17.             await LogDataAsync("Oops error occuered => ", exception);  
  18.         }  
  19.   
  20.         // After C# 6.0 Loging Exception  
  21.         try  
  22.         {  
  23.             throw new Exception("Something went wrong");  
  24.         }  
  25.         catch (Exception ex)  
  26.         {  
  27.             await LogDataAsync("Oops error occuered => ", ex);  
  28.         }  
  29.         finally  
  30.         {  
  31.             await LogDataAsync("Exception Logging Completed."null);  
  32.         }  
  33.     }  
  34.     public static async Task LogDataAsync(string message, Exception exception)  
  35.     {  
  36.         using (var file = File.AppendText("issue.log"))  
  37.         {  
  38.             await file.WriteLineAsync($"{message} {exception?.ToString()}");  
  39.         }  
  40.     }  
  41. }  
Adding Exception Filter

Well, in previous versions of C# what we'd need to do is actually write an if clause that checks that property. And in this case it will be a message, and we would check to see whatever value we cared about, and then take the action that we needed. But in C# 6.0, the syntax for these situations has been simplified by using the when keyword in an exception filter.

  1. class Program  
  2. {  

  3.     static async void Main(string[] args)  
  4.     {  
  5.         try  
  6.         {  
  7.             throw new Exception("Something went wrong");  
  8.         }  
  9.         //(ex.Message.Substring(0,7) == "Warning") this condition will return boolean value  
  10.         // However we can go ahead and paste the catch that we previously had so if it doesn't meet the first condition  
  11.         // with the warning then it will go ahead and log the file that we expect.  
  12.         catch (Exception ex) when (ex.Message.Substring(0, 7) == "Warning")  
  13.         {  
  14.             // Its Warning - do nothing   
  15.         }  
  16.         catch (Exception ex)  
  17.         {  
  18.             await LogDataAsync("Oops error occuered => ", ex);  
  19.         }  
  20.         finally  
  21.         {  
  22.             await LogDataAsync("Exception Logging Completed."null);  
  23.         }  
  24.     }  
  25.     public static async Task LogDataAsync(string message, Exception exception)  
  26.     {  
  27.         using (var file = File.AppendText("issue.log"))  
  28.         {  
  29.             await file.WriteLineAsync($"{message} {exception?.ToString()}");  
  30.         }  
  31.     }  
  32. }  
Auto properties initializer

You will likely appreciate auto-property initializers. Just as the name implies, you can initialize auto-properties default values with a little less work than you did in the past. C# 6.0 introduces a new feature, auto-property initializers. We no longer need a constructor, because in the back end, the compiler is assigning this value to a backing field. Have a look at the below code snippet.

  1. public class Employee  
  2.  {  
  3.      // Before C# 6.0 property initialization via Constructor  
  4.      public Employee()  
  5.      {  
  6.          EmployeeId = 10001;  
  7.          Name = "Jignesh";  
  8.          City = "Bangluru";  
  9.      }  
  10.      // After C# 6.0 Assign values using = sign   
  11.      // We no need constructor if we use below code  
  12.      public int EmployeeId { getset; } = 100000;  
  13.      public string Name { getset; } = "Jignesh";  
  14.      public string City { getset; } = "Bangluru";  
  15.  }  

Using getter only auto properties

Getter-only auto-properties are essentially read-only properties that let you omit a setter, leaving you with just the get. And as a result, the backing field of a getter-only auto-property becomes read-only. And just like we just saw in the above example, we can also initialize it with a value. But now, with getter-only auto-properties, your class can remain immutable and you can still get the convenience of the concise syntax of an auto-property.

  1. public class Employee  
  2.  {  
  3.      // Before C# 6.0 property initialization via Constructor  
  4.      public Employee()  
  5.      {  
  6.          EmployeeId = 10001;  
  7.          Name = "Jignesh";  
  8.          City = "Bangluru";  
  9.      }  
  10.      // After C# 6.0 Assign values using = sign   
  11.      // We no need constructor if we use below code  
  12.      public int EmployeeId { get; } = 100000;  
  13.      public string Name { get; } = "Jignesh";  
  14.      public string City { get; } = "Bangluru";  
  15.  }  

Converting to expression-bodied function member

Expression-bodied function members can work for both methods and properties if you have a method with one statement, and that statement can be represented as an expression.

Expression-bodied function members allow methods, properties and other kinds of function members to have bodies that are expressions instead of statement blocks, just like with lambda expressions.

  1. class Program  
  2. {  
  3.     public string FirstName { getset; }  
  4.     public string LastName { getset; }  
  5.   
  6.     public string GetFullName(string firstName, string lastName) => firstName + lastName;  
  7.     static async void Main(string[] args)  
  8.     {  
  9.         Program program = new Program();  
  10.   
  11.         Console.WriteLine(program.GetFullName("jignesh""Kumar"));  
  12.   
  13.         Console.ReadLine();  
  14.     }  
  15.      
  16. }  

Using Static

Using static is a new kind of using clause that lets you import static members of types directly into scope. In the below example we have used system.Console class using name space so we can directly use WriteLine method in our code where ever we want.

  1. using System;  
  2. using System.Console;  
  3. namespace CSharpFeatures  
  4. {  
  5.  static void Main(string[] args)  
  6.  {  
  7.      WriteLine("This message from WriteLine function");  
  8.   }   
That's it from my end!!!
 
Thank you .... I hope you have enjoyed reading my blog.

If you have any question or queries please feel free to ask and post comments below so I can answer your query.