Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Null Propagation Operator: A New Feature of C# 6.0

0.00/5 (No votes)
24 Apr 2015 1  
In this tip, we will learn about the new feature of C# 6.0, the Null Propagation Operator.

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.

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 receive 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.

C#
using System;  
public class Person  
{  
    public int Age { get; set; }  
}  
public class Book  
{  
    public Person Author { get; set; }  
}  
public class execution  
{  
    public static void Main(string[] args)  
    {  
        Book b1 = new Book();  
        int authorAge = b1.Author.Age; // Author property never initialized, 
                                       // there is no Person to get an Age from.  
    }  
}

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

C#
using System;  
public class Person  
{ public int Age { get; set; } }  
public class Book  
{ public Person Author { get; set; } }  
public class execution  
{  
    public static void Main(string[] args)  
    {  
        Book b1 = new Book();  
        try { int authorAge = b1.Author.Age; }  
        catch (NullReferenceException e) { Console.WriteLine(e.Message); }  
        Console.ReadKey();  
    }  
}

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 within 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:

C#
if (Employee.Name == null)  
{  
    Console.WriteLine("No Employee name provided");  
}

The same can be converted into a one-liner using the Conditional Access Operator in C# 6.

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.

C#
if (student != null && student.studentdetails != null)  
{  
    Console.WriteLine(student.studentdetails.Address);  
}  
else  
{  
    Console.WriteLine("No Address");  
}

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:

C#
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

C#
using System;  
namespace CSharpFeatures  
{  
    class NullPropagation  
    {  
        static void Main()  
        {  
            Student student1 = new Student();  
            student1.Name = "Siddharth";  
            student1.rollno = 12;  
            student1.studentdetails = new Details() 
            { Address = "Lakshmi Nagar New Delhi India", Email = "abcd@xyz.com" };  
  
            Student student2 = new Student();  
            student2.Name = "Aditya";  
            student2.rollno = 05;  
            student2.studentdetails = new Details() { Address = null, Email = null };  
  
            Console.WriteLine("Student 1:\n");  
            if (student1.Name == null) Console.WriteLine("No Name Provided");  
            else Console.WriteLine(student1.Name);  
            if (student1.studentdetails.Address == null) Console.WriteLine(" No Address Provided");  
            else Console.WriteLine(student1.studentdetails.Address);  
            if (student1.studentdetails.Email == null) Console.WriteLine("No Email Address Provided");  
            else Console.WriteLine(student1.studentdetails.Email);  
            Console.WriteLine("\nStudent 2:\n");  
            if (student2.Name == null) Console.WriteLine("No Name Provided");  
            else Console.WriteLine(student2.Name);  
            if (student2.studentdetails.Address == null) Console.WriteLine("No Address Provided");  
            else Console.WriteLine(student2.studentdetails.Address);  
            if (student2.studentdetails.Email == null) Console.WriteLine("No Email Address Provided");  
            else Console.WriteLine(student2.studentdetails.Email);  
            Console.ReadLine();  
        }  
    }  
    class Student  
    {  
        public string Name { get; set; }  
        public int rollno { get; set; }  
        public Details studentdetails { get; set; }  
    }  
    class Details  
    {  
        public string Address { get; set; }  
        public string Email { get; set; }  
    }  
}

Output

VS13 Output

Demo Application using Visual Studio 2015 Preview

C#
using System;  
using System.Console;  
namespace CSharpFeatures  
{  
    class NullPropagation  
    {  
        static void Main()  
        {  
            Student student1 = new Student();  
            student1.Name = "Siddharth";  
            student1.rollno = 12;  
            student1.studentdetails = new Details()  
            { Address = "Lakshmi Nagar New Delhi India", Email = "abcd@xyz.com" };  
  
            Student student2 = new Student();  
            student2.Name = "Aditya";  
            student2.rollno = 05;  
            student2.studentdetails = new Details()  
            { Address = null, Email = null };  
            WriteLine("Student 1:\n");  
            WriteLine(student1?.Name ?? "No Name");  
            WriteLine(student1?.studentdetails?.Address ?? "No Address");  
            WriteLine(student1?.studentdetails?.Email ?? "No Email provided");  
            WriteLine("\nStudent 2:\n");  
            WriteLine(student2?.Name ?? "No Name");  
            WriteLine(student2?.studentdetails?.Address ?? "No Address");  
            WriteLine(student2?.studentdetails?.Email ?? "No Email provided");  
            ReadLine();  
        }  
    }  
    class Student  
    {  
        public string Name { get; set; }  
        public int rollno { get; set; }  
        public Details studentdetails { get; set; }  
    }  
    class Details  
    {  
        public string Address { get; set; }  
        public string Email { get; set; }  
    }  
}

Output

VS15 Output

Summary

In this tip, 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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here