C# 6.0 New Features

  • Expression Bodied Members For Properties and Indexers in C# 6.0

    In one of the earlier post blogged under new features in C# 6.0, we saw how we can make use of the Expression bodied functions to get rid of the one liner functions to increase the readability and maintainability of the code. Likewise we can also create expression bodied methods for properties instead of the classic getter method. For example let’s take a note of code given below which is using the classic way of creating and initializing the property.

    Here we have a readonly property called FullName for which value is created by concactnating FirstName and LastName property in the getter method.

    As you saw in the earlier post we can make use of the lambda arrow(=>) instead of the code block enclosed in curly braces({}) to define the body of the getter method. The syntax is pretty straightforward

    property name => expression


  • Await in Catch and Finally Block in C# 6.0

    In C# 5.0 Microsoft introduced asynchronous programming using the async and await keywords, but there was significant restriction for using await in catch and finally blocks. This was due to some specific issues in the compiler and with C# 6.0 they code in the compiler has undergone some changes to make it work. This was one of the most requested features from the developers worldwide because they resorted to write some complex logic in the catch block to overcome this restriction

    Let’s take an example, in the earlier version if we write the code given below, we will get an compile error.


  • Expression Bodied Methods in C# 6.0

    As developers we have created functions with a single statement that just return trivial values or expressions. Expression bodied function helps us to make our code more readable and concise. Normally we do write functions with statements being surrounded by curly braces be it for single line or for multiple lines of code. A typical example is given below

    In C# 6.0, it’s now possible to write function bodies as lambda expression. We will make use of the lambda arrow(=>) instead of the curly braces({}). So we will see how we can transform the earlier code to make use of the expression bodied functions.


  • Exception Filtering in C# 6.0

    Since its inception C# has been able to filter exceptions depending on the type of the exception. For example, while trying to access a resource from the file system, there are possibilities of different types of errors popping up like timeout, invalid handle, invalid operation etc. To handle these kind of scenarios we could simply have different catch block for each exception type like the sample given below

    try
    {
        using (StreamReader reader = new StreamReader("invalid-file.txt"))
        {
            reader.ReadToEnd();
        }
    }
    catch(FileNotFoundException e)
    {
    }
    catch(IOException e)
    {
    
    }
    catch(Exception e)
    {
        //all other exceptions
    }
    
    

     

    But sometimes we may want the catch block to execute if and only if an additional condition is also met. So normally we will put in a conditional check inside catch block as shown below.


  • Using static statement in C# 6.0

    The using static is another neat little feature introduced in C# 6.0 which helps you to make your code more readable as well as helps to avoid some redundancy in your code.

    We all know that we can import a namespace with using which helps us to use the type name without using the fully qualified name. For example, in most of the programs the first statement will be using System and if we want to call the WriteLine method using the statement given below,

     

    using System;

    public class Program
    {
        public static void Main()

        {

            Console.WriteLine("This is a test");

         }

    }

    Suppose if we didn't imported the namepsace then, instead of Console.WriteLine() we need to call the method with the fully qualified name. ie System.Console.WriteLine() 

    public class Program
    {
        public static void Main()

        {

            System.Console.WriteLine("This is a test");

         }

    }

    Imagine a class with a large number of calls to the WriteLine method and we will be having a lot of redundant 

    code for the owner class, in this case System

    Let's take the below code as an example


  • nameof Expression in C# 6.0

    This function is one of the useful addtion to the language in C# 6.0 and will see a widespread adoption. We as developers have written many times the below code numerous times in our life.

    In this basically we are checking whether the parameters are properly set according the business rules and if it's not then throws the ArgumentNull exception with the message saying that this particular property is not set.

    Suppose after some time we decided to change the name of the properties, went ahead with using the refactoring options available in Visual Studio. In the example I removed the term Product from all the properties using the refactoring option, but the messages for the ArgumentNull exception won't change since it's inside string literals.

    Now when the exception occurs there is a mismatch between the actual property name and the name in the message. Imagine if this occurs in a class containing a lot of properties then it take some time to make the corrections and also there's a possiblity of missing out on some.


  • Auto Properties in C# 6.0

    C# 6.0 brings the ability to initialize an auto-properties pretty much like the way we do for a field. This helps you to intialize the backing field without woking through the setter of the auto property or making using of a local variable. It's executed in the order as written and not at the time when the object is initialized. It means that we cannot reference it using this keyword since the property iniitialization happens before the object intialization.

    In the earlier versions, suppose if we want to initialize the properties to some default values we were doing that at the time of instantiating an object as shown below

    In C# 6.0, now it's possible to initialize the values for the properties at the time of declaration itself.

    Many of you may be wondering why I am using a $ symbol in front of the string and how can I use the C# syntax inside the string which is later transformed into the correct message during execution of the code. It's the new String interpolation feature in C# 6.0 and you read more about it here.

    And you can mix and match the defaults with the ones you want as shown below. In this example, I have modified the default values at the time of instantiation for FirstName and LastName properties and left the Email property untouched

    Also we can initialize it without a setter also.


  • Dictionary Initializers in C# 6.0

    Dictionary initialization was first introduced with C# 3.0 and the syntax for the same remained same since then.

    In C# 6.0 the syntax was tweaked little bit to make it more friendly to maintain. As we all know in a dictionary object, information is stored as key value pairs and if you look at the above syntax a lot of curly brackets and punctuation marks are used. This makes it pretty ugly and doesn’t reflect the data structure which is holding the data.

    The new syntax reduces the number of keystrokes and the code is now more elegant and readable by omitting some curly braces and the syntax now uses the equals sign which helps you to recognize the info in a key value pair format

    Even though they have introduced a new way on initializing dictionary objects, the old way of writing is still valid and it’s up to you developers to use which one.


  • String Interpolation in C# 6.0

    Up untill now we are using various options for formatting strings using String.Format or by concatenating string values using + operator or String.Concat function. 

    In the case of using + operator , as the number of items that needs to concatenated increases it becomes very hard to maintain and to understand what we are doing and some times it may result in incorrect string ouput too.

    This can be solved to some extent by using the String.Format function by using the literals as placeholders so that we will get to know what the output be in advance by looking at the text part. But here we may find problems if we don't give the parameter values in the same order as in the string text part. Also if the number of placeholders and the values in the parameter list are not in sync an exception will be thrown at runtime.

    In C# 6.0, Microsoft added a new feature to make our life easier by allowing us to put the expressions directly in the string literal. Now we can inject the values into a string using curly bracket enclosed expressions.


  • Null Propagation Operator in C# 6.0

    Every developer who writes C# code should have encountered NullReference exception or Object Reference not set to an instance of an object error at least once. This error normally happens when you try to invoke a member of an object without performing a null check on the object. For example the following code will produce a compiler error

     

    So normally to solve this issue we will introduce a conditional checking before invoking the property as shown below