Null – Conditional Operators in C# 6.0

Null – Conditional Operators in C# 6.0

Along with the nameof operator, 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.

Consider we have class called Student, and which having another property Address of type Address class. Now we can have the following code snippet to print the HomeAddress.

if (student != null && student.Address != null)
{
WriteLine(student.Address.HomeAddress);
}
else
{
WriteLine("No Home Address");
}

As we can see, to avoid  the null-reference exception, we have checked the null for student, and student.Address as they can have null reference as object.

Now, the above code block can be re-written using null – conditional ( ?.) operator as follows:

WriteLine(student?.Address?.HomeAddress ?? "No Home Address");

Isn’t it really nice. 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.  Following image illustrate how the ?. works.

 

Null - Conditional Operator

Must Read : What’s new in C# 6.0

It also works nicely with methods, mainly when we triggers any events. Instead of writing

if (AddressChanged != null)
{
AddressChanged (this, EventArgs.Empty);
}

Using ?. we can rewrite,

AddressChanged ?.Invoke(this, EventArgs.Empty);
Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

5 Comments to “Null – Conditional Operators in C# 6.0”

  1. Bo

    this is a nice little nugget of info to know. I had enjoying using similar syntax in Swift and was thinking how nice it would be to do the same in C#. And now I know we can do the same. Thanks!

  2. Boise Internet Marketing

    I love this!!! This is by far my favorite feature of C# 6…I can hardly wait for it to be released!

Comments are closed.