Null-conditional operator

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

Null-conditional member access is a great new feature that, I think, will help make code more bullet-proof and easier to read.

How often have you seen code like this:

MyResult mr = null;
if(ob != null)
{
  MyClass mc = ob.SomeMethod();
  if(mc != null)
  {
    MyClass2 mc2 = mc.SomeOtherMethod();
    if(mc2 != null)
      mr = mc2.SomeThirdMethod();
  }
}

or, worse:

 MyResult mr = ob.SomeMethod().SomeOtherMethod().SomeThirdMethod();

with absolutely no null checks at all. A common trick is to use the ternary operator:

MyClass mc = (ob != null) ? ob.SomeMethod() : null;
MyClass2 mc2 = (mc != null) ? mc.SomeOtherMethod() : null;
MyResult mr = (mc2 != null) ? mc2.SomeThirdMethod() : null;

which is better, but still somewhat verbose. Enter null-conditional operators:

MyResult mr = ob?.SomeMethod()?.SomeOtherMethod()?.SomeThirdMethod();

The ?. can be read as “If the thing on the left is not null, then call the thing on the right. Otherwise, just return null and stop processing.”

To be fair, I think that it is probably not a great idea to create huge chains of code using this, but used in moderation, I think that it a) makes code easier to read and b) encourages coders to actually do a null check, since it is quicker, and less verbose.

Note that this also works with indexers:

string name = myList?[1]?.Name;

This will short circuit if myList is null or if the item at position 1 in the array is null. Note, however, that if the list has less than 2 items, you will still get an exception – the code checks for nulls, not bounds.

Another cool use for the null-conditional is when dealing with events. Rather than having to check to see if the event handler is defined, you can just do this:

SomeHandler?.Invoke(this,args);

Which also has the advantage of being thread-safe. It is very common to see code like this:

if(SomeHandler != null)
  SomeHandler(this, args);

Which is fine almost all of the time — except if a different thread happens to unsubscribe to the event sometime between the check and the call. Technically, the correct code would be:

var handler = SomeHandler;
if(handler != null)
  handler(this, args);

I remember early discussions about the C# language where the discussion was whether there needed to be special handling for this to be thread-safe without the extra code. The feeling was that most of the time, this wasn’t enough of a risk to make it worth extending the language, but the null-conditional operator takes care of it now anyway.

Here are links to posts about other new features in C# 6.0:

Leave a Reply

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

*