Whats new in C# 6.0

  • Exception Filters : Exception filters are a CLR capability that is exposed in Visual Basic and F#, but hasn’t been in C# – until now. If the parenthesized expression after ‘if’ evaluates to true, the catch block is run, otherwise the exception keeps going. Basically Exception Filter is one of the new features of C# 6.0 that allows us to specify a conditional clause for each catch block. In other words now we can write a catch block that will handle the exception of a specific type only when a certain condition is true that is written in an exception filter clause. First we see a code snippet of an Exception Filter then we will learn more about it.
        static void Main(string[] args)
        {
            try
            {
                throw new ArgumentNullException("Arg1");
                //throw new ArgumentNullException("Arg2");
            }
            catch (ArgumentNullException ex) if (ex.Message.Contains("Arg1"))
            {
                Console.WriteLine("Error Message : " + ex);
            }
            catch (ArgumentNullException ex) if (ex.Message.Contains("Arg2"))
            {
                Console.WriteLine("Error Message : " + ex);
            }
        }
    }
  • Await in catch and finally blocks : This has been disallowed until now, now with C# 6.0 we can use await int catch and finally block.
        public async void Process()
        {
            ILogger logger = new Logger();
            try
            {
     
            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine("Error Message : " + ex);
                await logger.LogError(ex);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Message : " + ex);
                await logger.LogError(ex);
            }
            finally
            {
                await logger.Log("Method Execution Process() Completed");    
            }
        }
    }

    Logger Implementation looks some thing like this

    public interface ILogger
     {
         Task<bool> LogError(Exception ex);
     
         Task<bool> Log(string message);
     }
     public class Logger : ILogger
     {
         public async Task<bool> LogError(Exception ex)
         {
             await Task.Run(() => {
                 // Log to Windows Log or do custom logging
             });
             return true;
         }
     
         public async Task<bool> Log(string message)
         {
             await Task.Run(() => {
                 // Log to Windows Log or do custom logging
             });
             return true;
         }
     }
  • Auto-property initializers: These are similar to initializers on fields. Initialize property is repetitive task, and cannot be done in the same line as we can can done for fields.  Property can be initialized only in the constructor, beside the filed which can be initialized in the same line where it is declared.
     public class Employee
     {
         private string _firstName = "Default Name";
         public string FirstName { getset; }
         public Employee()
         {
             FirstName = _firstName;
         }
     
     }

    The new feature in C# 6.0 defines Auto-Property initializer alowing property to be initialized like fields. The following code snippet shows the Auto-Property Initializer;

    public class Employee
     {
         private static string _lastName = "Gote";
         public string FirstName { getset; } = "Aamol";
     
         public string LastName { getset; } = "Gote";
     
         //Property with Private Setter
         public string Email { get; } = _lastName;
     }
  • Expression-bodied function members: It allow methods, properties and other kinds of function members to have bodies that are expressions instead of statement blocks, just like with lambda expressions.Expression-bodied function members allow properties, methods, operators and other function members to have bodies as lambda like expressions instead of statement blocks. Thus reducing lines of codes and clear view of the expressions. Now in C# 6.0, instead of writing the whole property body using getters/setters, you can now just use the lambda arrow (“=>”) to return values. Yu can write expressions for methods/functions which returns value to the caller example below
    public string GetFullName(string firstName, string lastname, string middleInitial) => string.Concat(firstName, " ", lastname, " ", middleInitial);
    

    Same can be applied to properties as well

    public string StreetAddress => "1 Microsoft Way Redmond";
    
  • Import Features : using static is a new kind of using clause that lets you import static members of types directly into scope.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Console;
     
    namespace WhatNewInCharp6
    {
        class Program
        {
            static void Main(string[] args)
            {
                WriteLine("Inside Main");
            }
        }
    }
  • Null Conditional Operator: The NullReferenceException is night mare for any developer. Almost every created object must be check against null value before we call some of its member.C# 6.0 also introduced Null-Conditional operator that enable developers to check the null value with in an object reference chain. The null – conditional operator ( ?.) , returns null if anything in the object reference chain in null. This avoid checking null for each and every nested objects if they are all in referenced and having null values.
    For E.g. Consider below classes

    public class Person
    {
        public Address Address { getset; }
    }
     
    public class Address
    {
        public Address HomeAddress { getset; }
        public Address OfficeAddress { getset; }
        public string StreetAddress { getset; }
        public string City { getset; }
        public string State { getset; }
        public string Zip { getset; }
    }

    I need to access Home Address for Person Object Passed and then print it, in older appraoch i had to do all nested null check like shown below

    public void PrintHomeAddress(Person person)
    {
        if (person != null && person.Address != null & person.Address.HomeAddress != null)
        {
            Console.WriteLine(string.Concat(person.Address.HomeAddress.StreetAddress, Environment.NewLine, person.Address.HomeAddress.State, person.Address.HomeAddress.Zip));
        }
    }

    But with C# 6.0 null conditional operator same can be achieved like show below

    public void PrintHomeAddressNewWay(Person person)
    {
        if (person?.Address?.HomeAddress != null)
        {
            Console.WriteLine(string.Concat(person.Address.HomeAddress.StreetAddress, Environment.NewLine, person.Address.HomeAddress.State, person.Address.HomeAddress.Zip));
        }
    }

    Instead of check each and individual objects, using ?. we can check entire chain of reference together and whenever there is a null values, it return null.
    The “?.” operator is basically saying, if the object to the left is not null, then fetch what is to the right, otherwise return null and halt the access chain.

  • nameOf Expressions: nameof expressions are a new form of string literal that require more syntax and are more restricted than the existing kinds. Oftentimes you need to provide a string that names some program element: when throwing an ArgumentNullException you want to name the guilty argument; when raising a PropertyChanged event you want to name the property that changed, etc. Using ordinary string literals for this purpose is simple, but error prone. You may spell it wrong, or a refactoring may leave it stale. nameof expressions are essentially a fancy kind of string literal where the compiler checks that you have something of the given name, and Visual Studio knows what it refers to, so navigation and refactoring will work.
    Earlier for arguement null exception you would do some thing like shown below, but what if parameter name person changes, then you change the exception message as well

    public void PrintOfficeAddress(Person person)
     {
        if (person == nullthrow new ArgumentNullException("person is null");
     }

    With C# 6.0 you use nameOf Operator which will automatically factor in your variable name change in case code gets re-factored or parameter name changes

    public void PrintOfficeAddressNewWay(Person person)
    {
        if (person == nullthrow new ArgumentNullException(nameof(person) + " is null");
    }
    
  • String Interpolation: We regularly use string.Format or string.Concat or “+” operator to do all kinds of string manipulations like shown below
    public void PrintPersonName(Person person)
    {
        Console.WriteLine(string.Format("Full Name: {0} {1} {2}", person.FirstName, person.LastName, person.MiddleInitial));
    }

    String interpolation lets you more easily format strings. String.Format and its cousins are very versatile, but their use is somewhat clunky and error prone. Particularly unfortunate is the use of numbered placeholders like {0} in the format string, which must line up with separately supplied arguments

    With C# 6.0 above can be achieved easily as shown below

    public void PrintPersonNameNewWay(Person person)
    {
        Console.WriteLine("Full Name: \{person.FirstName} \{person.LastName} \{person.MiddleInitial}");
    }
  • Dictionary Initializer – You can initialize dictionary in following manner
    Dictionary<stringPerson> persons = new Dictionary<stringPerson>()
     {
         ["EMPID1"] = new Person() { FirstName = "Aamol", LastName = "Gote" },
         ["EMPID2"] = new Person() { FirstName = "John", LastName = "Doe" },
         ["EMPID3"] = new Person() { FirstName = "Mary", LastName = "Lamb" }
     };

    If the Key is not string but some object then syntax would be some thing like below

    Dictionary<IdentifierPerson> personsWithIdentifiers = new Dictionary<IdentifierPerson>()
    {
        [new Identifier() { Id = new Guid(), SSN = "111-222-2345" }] = new Person() { FirstName = "Aamol", LastName = "Gote" },
        [new Identifier() { Id = new Guid(), SSN = "345-222-2345" }] = new Person() { FirstName = "John", LastName = "Doe" },
        [new Identifier() { Id = new Guid(), SSN = "999-222-2345" }] = new Person() { FirstName = "Mary", LastName = "Lamb" }
    };

Following features have not made in to VS2015 Preview

  • Primary constructors in C# (along with initializers in structs)
  • Declaration expressions in C# / Out parameters in VB

Source Code be downloaded from here

Advertisements

One thought on “Whats new in C# 6.0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s