Null Propagation Operator: A New Feature of C# 6.0

Introduction

On November 12, 2014, the day of the Visual Studio Connect() event, Microsoft announced Visual Studio 2015 Preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0 that came with many improvements and new features. One of the newly introduced features of C# 6.0 is the Null Propagation Operator.

Don't forget to read my previous posts on this series: "A new feature of C# 6.0".

    System.NullReferenceException: Object reference not set to an instance of an object.

    System.NullReferenceException is a very common exception that indicates we are trying to access member fields, or function types, on an object reference that points to null or is not present in the code. We receives this exception when we have not checked for a null in our code. This exception is also known as Object reference not set to an instance of an object. Let's see how we get a NullReferenceException and how to handle it.

    1. using System;  
    2. public class Person  
    3. {  
    4.     public int Age { getset; }  
    5. }  
    6. public class Book  
    7. {  
    8.     public Person Author { getset; }  
    9. }  
    10. public class execution  
    11. {  
    12.     public static void Main(string[] args)  
    13.     {  
    14.         Book b1 = new Book();  
    15.         int authorAge = b1.Author.Age; // Author property never initialized, there is no Person to get an Age from.  
    16.     }  
    17. }  

    When we run this code snippet, an unhandled exception of type "System.NullReferenceException" occurs in our application.

    unhandled exception

    Now we can handle this exception using try {} and catch {} blocks.

    handling exception

    1. using System;  
    2. public class Person  
    3. public int Age { getset; } }  
    4. public class Book  
    5. public Person Author { getset; } }  
    6. public class execution  
    7. {  
    8.     public static void Main(string[] args)  
    9.     {  
    10.         Book b1 = new Book();  
    11.         try { int authorAge = b1.Author.Age; }  
    12.         catch (NullReferenceException e) { Console.WriteLine(e.Message); }  
    13.         Console.ReadKey();  
    14.     }  
    15. }  

    Output

    exception handled

    Since we are using the new keyword that only creates a new instance of the class Book, but does not create a new instance of the class Person, the Author property is still null.

    All programmers want their program to terminate in abnormal conditions. So to avoid this, checking for a null value of every member is useful. C# 6.0 has introduced the Null-Propagation Operator (?.) that enables developers to check for the null value in an object reference chain.

    What is Null Propagation Operator

    C# 6.0 introduced many new features in Visual Studio 2015 Preview. Let's have a look at one of its new features, the Null Propagation Operator. In earlier versions of the C# language, we always had to write an if condition for a null check before using an object or its property. Now C# 6.0 has introduced the Null-Propagation Operator (?.) that enables developers to check for the null value with in an object reference chain. The null-propagation operator (?.) will return null if anything in the object reference chain is null. We need a better way of handling null exceptions where null propagation exists. The null propagation operator can now be used like nullable types by putting a question mark (?) after the instance before calling the property. We don't need to write additional if statements to check for the null values.

    Example 1

    In earlier versions of the C# language, you always had to check for nulls explicitly before using an object or its property, as shown below.

    1. if (Employee.Name == null)  
    2. {  
    3.     Console.WriteLine("No Employee name provided");  
    4. }  
    The same can be converted into a one-liner using the Conditional Access Operator in C# 6.

    1. Console.WriteLine(Employee?.Name ?? "No Employee name provided");  

    Example 2

    Suppose we have a class called Student that has another property studentdetails of type Details class. Now we can have the following code snippet to print the Address.

    1. if (student != null && student.studentdetails != null)  
    2. {  
    3.     Console.WriteLine(student.studentdetails.Address);  
    4. }  
    5. else  
    6. {  
    7.     Console.WriteLine("No Address");  
    8. }  

    As we can see, to avoid the null-reference exception, we have checked the null for student and student.studentdetails since they can have a null reference as object. So, the preceding code snippet can be re-written using the null propagation operator (?.) as follows:

    1. Console.WriteLine(student?.studentdetails?.Address ?? "No Address");  

    Both code snippets will provide us the address of the student.

    prints address

    What I think is, it's a really nice feature because instead of checking each and individual objects, using the null propagation operator (?.) we can check the entire chain of references together and whenever there is a null value in the entire chain of reference, it will return null.

    Demo application using Visual Studio 2013

    1. using System;  
    2. namespace CSharpFeatures  
    3. {  
    4.     class NullPropagation  
    5.     {  
    6.         static void Main()  
    7.         {  
    8.             Student student1 = new Student();  
    9.             student1.Name = "Siddharth";  
    10.             student1.rollno = 12;  
    11.             student1.studentdetails = new Details() { Address = "Lakshmi Nagar New Delhi India", Email = "[email protected]" };  
    12.   
    13.             Student student2 = new Student();  
    14.             student2.Name = "Aditya";  
    15.             student2.rollno = 05;  
    16.             student2.studentdetails = new Details() { Address = null, Email = null };  
    17.   
    18.             Console.WriteLine("Student 1:\n");  
    19.             if (student1.Name == null) Console.WriteLine("No Name Provided");  
    20.             else Console.WriteLine(student1.Name);  
    21.             if (student1.studentdetails.Address == null) Console.WriteLine(" No Address Provided");  
    22.             else Console.WriteLine(student1.studentdetails.Address);  
    23.             if (student1.studentdetails.Email == null) Console.WriteLine("No Email Address Provided");  
    24.             else Console.WriteLine(student1.studentdetails.Email);  
    25.             Console.WriteLine("\nStudent 2:\n");  
    26.             if (student2.Name == null) Console.WriteLine("No Name Provided");  
    27.             else Console.WriteLine(student2.Name);  
    28.             if (student2.studentdetails.Address == null) Console.WriteLine("No Address Provided");  
    29.             else Console.WriteLine(student2.studentdetails.Address);  
    30.             if (student2.studentdetails.Email == null) Console.WriteLine("No Email Address Provided");  
    31.             else Console.WriteLine(student2.studentdetails.Email);  
    32.             Console.ReadLine();  
    33.         }  
    34.     }  
    35.     class Student  
    36.     {  
    37.         public string Name { getset; }  
    38.         public int rollno { getset; }  
    39.         public Details studentdetails { getset; }  
    40.     }  
    41.     class Details  
    42.     {  
    43.         public string Address { getset; }  
    44.         public string Email { getset; }  
    45.     }  
    46. }  

    Output

    VS13 Output

    Demo application using Visual Studio 2015 Preview

    1. using System;  
    2. using System.Console;  
    3. namespace CSharpFeatures  
    4. {  
    5.     class NullPropagation  
    6.     {  
    7.         static void Main()  
    8.         {  
    9.             Student student1 = new Student();  
    10.             student1.Name = "Siddharth";  
    11.             student1.rollno = 12;  
    12.             student1.studentdetails = new Details()  
    13.             { Address = "Lakshmi Nagar New Delhi India", Email = "[email protected]" };  
    14.   
    15.             Student student2 = new Student();  
    16.             student2.Name = "Aditya";  
    17.             student2.rollno = 05;  
    18.             student2.studentdetails = new Details()  
    19.             { Address = null, Email = null };  
    20.             WriteLine("Student 1:\n");  
    21.             WriteLine(student1?.Name ?? "No Name");  
    22.             WriteLine(student1?.studentdetails?.Address ?? "No Address");  
    23.             WriteLine(student1?.studentdetails?.Email ?? "No Email provided");  
    24.             WriteLine("\nStudent 2:\n");  
    25.             WriteLine(student2?.Name ?? "No Name");  
    26.             WriteLine(student2?.studentdetails?.Address ?? "No Address");  
    27.             WriteLine(student2?.studentdetails?.Email ?? "No Email provided");  
    28.             ReadLine();  
    29.         }  
    30.     }  
    31.     class Student  
    32.     {  
    33.         public string Name { getset; }  
    34.         public int rollno { getset; }  
    35.         public Details studentdetails { getset; }  
    36.     }  
    37.     class Details  
    38.     {  
    39.         public string Address { getset; }  
    40.         public string Email { getset; }  
    41.     }  
    42. }  

     Output

    VS15 Output

    Summary

    In this article we learned about the new feature of C# 6.0, the null propagation operator that will definitely improve the developer's productivity by reducing the number of lines in a code and also by reducing the numbers of bugs in the code and will keep the code clean. Don't forget to read my other articles on the series "A new feature of C# 6.0". Share your opinion about this feature and how you will use it in your project. Your comments are most welcome. Happy Coding!


    Similar Articles