Click here to Skip to main content
15,882,063 members
Articles / Programming Languages / C#
Tip/Trick

Null Propagation Operator: A New Feature of C# 6.0

Rate me:
Please Sign up or sign in to vote.
5.00/5 (12 votes)
24 Apr 2015CPOL4 min read 74.4K   17   8   3
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Tester / Quality Assurance
India India
Hello this is Abhishek working as a Software Test Engineer

Comments and Discussions

 
QuestionAdditional propagation usage Pin
kae367-Jan-20 10:17
kae367-Jan-20 10:17 
QuestionThanks for being the "messenger" Pin
Bill Gord27-Apr-15 12:03
professionalBill Gord27-Apr-15 12:03 
BugOperator Name Pin
Verious26-Apr-15 14:24
Verious26-Apr-15 14:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.