Null – Conditional Operators in C# 6.0

By | December 10, 2014

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("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);

5 thoughts on “Null – Conditional Operators in C# 6.0

  1. Pingback: Download PPT – “A lap around C# 6.0 and Visual Studio 2015 Preview” – MUGH Dev Day– 29th Nov 2014 | Abhijit's World of .NET

  2. Pingback: 10 New features of C# 6.0 that you should know | Abhijit's World of .NET

  3. 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!

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