Null-propagating operator / Null-Conditional Operator feature in C# 6.0

Saturday, August 09, 2014 0 Comments A+ a-


I am telling today about  Null-propagating operator / Null-Conditional Operator ?. a new proposed feature in C# 6.0, it is a very nice feature what i think is because it makes things more simpler and one liner.

Suppose i have some class X and in which i have a property which is another class Y and then in Y and i have a property Z.

and if i am accessing somewhere in code i would have to check if X is not null then access Y and if Y is not null then access Z.

Normally we would do it this way:

if(X != null && X.Y != null)
   string value = X.Y.Z.ToString();

but now we have a very simpler solution for this:

string value = X?.Y?.Z;

and thats it, now this will make sure that X and Y are not null before getting the Z, it is now safe way to access the Z.

X?.Y?.Z means: 
  • first, check if X is not null, then check Y otherwise return null,
  • second, when X is not null then check Y, if it is not null then return Z otherwise return null.
The ultimate return value will be Z or null.

Without this operator if x is null, then accessing X.Y would raise a Null Reference Exception, the Null-Conditional operator helps to avoid explicitly checking for null.

It is a way to avoid Null Reference Exception.
Coursera - Hundreds of Specializations and courses in business, computer science, data science, and more