Skip to content

Null Conditional Operator

There are a bunch of cool features coming in C#6, but the one I’m looking forward to the most is the Null Conditional Operator.  Developers write a lot of code to check if a value is null.  Sometimes it creates a deep and ugly nest of if statements.  Let’s say you are trying to find a customer’s primary contact’s city, it might look like this:

Or maybe you prefer less nesting and instead use a longer if statement:

With the new Null Conditional Operator you can just put ?. in place of the .. If the value to the left of the ?. is null it returns null otherwise it returns the property to the right. These two bits of code return the same thing:

So the deep nest from above can be re-written as:

It starts to get some real power when you use it in combination with the Null Coalescing Operator ?? In the following code we return the City as ‘Unknown’ if the PrimaryContact is null, or if the Address is null, or the City is null.

Published inC#
  • http://branonsoftware.blogspot.com/ Brandon

    Pretty cool, thanks for sharing!