Null propagating operator in C# 6.0

Something I’ve been wanting for years in .Net (c# specifically) is a cleaner way to detect null objects before trying to access properties or methonds on said objects. Just today I noticed that C# 6.0 (along with Visual Studio 2014) will finally make this a bit easier. 

In the past, before you access a property on an object, you would want to make sure it’s not null first. So instead of doing: 

var val = myobject.myValue; 

You would want to add null checking code like this: 

 

if(myObject != null){

   var val = myObject.myValue; 

}

Multiply this code by thousands of times, and it becomes a huge headache to look at, maintain, or even test. 

So: Null propagation operator (or, null propagating operator) to the rescue. We can replace the “.” with a “?.” operator to have the system check the object for null prior to accessing a property. So our c# 6.0 version of the above will now look like this: 

var val = myObject?.myValue; 

val will take on the type of myValue, or rather, a nullable version of the type of myValue. So if myValue is an int, val will be an int?. 

We can also combine this with the null coalescing operator to provide a default value, and keep val as a normal int:

var val = myObject?.myValue ?? 0; 

Looking forward to using this in future projects. 

Leave a Reply

Your email address will not be published. Required fields are marked *