C# features: null coalesce & conditional operator

In C# we have nullable types and references which can be null. When we access them in a null state, a NullReferenceException is flying towards us.

There are cases, when the null object pattern may reduce null checks, but there still remain many places in your code where you have to implement them.

Let’s have a look at two C# features for null checking.

Null coalesce operator

When you handle variables that may be null, you often have to check if they are null and if they are, use a default value.
To make this task as simple as possible C# has the null coalescing operator ??, which works similar to a ternary / conditional operator with an == null condition.

NULL conditional OPERATORs (C# 6)

The two new operators ?. and ?[ make null checking easier and eliminate boilerplate code. The ? means that the element on the right is only accessed when it’s not null. ?. is used for references and ?[ for arrays.

Let’s look at an example:


Our code should be as simple and as expressive as possible. C# has 2 convenient features that help us to archive this goal.

I definitely recommend to try this features to see yourself how this cleans your code- for example LINQ, EF, WebRequests and so on.