C#6: Null-conditional operators

With the release of Visual Studio 2015 in July came C# 6. Each iteration of C# has tended to have a theme and if there were a theme for this one, it would be developer productivity; all the new features in C# 6 appear to be either improvements to existing features, or syntactical shortcuts to simplify common operations. One of those syntactical shortcuts is the ?. operator1, which is accompanied by the similar ?[] operator2.

These new operators are collectively known as null-conditional operators. Most, if not all C# developers have used the null-coalescing operator, ?? and found it to be brilliant…until the next step was to call a method or property on the result. Though (something ?? somethingelse).Property seems like it might be a good idea, there is rarely a suitable somethingelse that doesn't just feel like hack, so invariably, we resort to an if or the conditional operator, ?:3.

Or, if using an indexer:

In C# 6, the ?. and ?[] operators step up to help. These new null-conditional operators check the value on the left of the operator and, if it is null, return null, short-circuiting the remainder of the expression; if the value on the left of the operator is non-null, the expression continues according to precedence rules.

Using these operators, we can express our earlier code much more succinctly and without resorting to convoluted, hacky ?? chains.

There isn't much else to write about these simple operators except to draw attention to how ?. works with Nullable<T> types such as int?4. Consider the ?? operator. When the ?? operator is applied to a nullable type like int?, it either returns the value wrapped in that int? or the value evaluated from the right of the operator. That is to say that instead of needing to reference the Value property of the nullable directly, the operator does that for you. The following assignment works because x.Value is returned from the ?? operator, not x.

The ?. operator works the same way, which means the following does not make sense and won't compile; Value is not a property of int:

Whereas this will work just fine:

In Conclusion…

The null-conditional operators, ?. and ?[] provide some shortcuts that will no doubt lead to clearer code, and I welcome their addition to the C# language. I hope that you do to.

 


  1. aka, the one-eyed Elvis operator 

  2. the robot Elvis, or Howard The Duck 

  3. The two-eyed Elvis 

  4. also expressible as Nullable<int> 

3 thoughts on “C#6: Null-conditional operators”

Leave a Reply

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