C# - the null-conditional Operator and how to avoid nested if statements

You probably ended up here because you wanted to avoid nested if statements or found a question mark (?) symbol in a code base and wondered what it did. Perhaps you are just looking for an easy way to do null checks. From C# 6 and on there is the Null-Conditional operator, which is sugar syntax that makes your code easier to read and comprehend. But of course this is only true, if you understand what it does! It is simply a way to make null checks in an easy and chained way, which can reduce nesting in your code.

Take a look at the example below. If the users variable is null, then the amount variable will be null, but if users is not null it will be whatever count returns.

var amount = users?.Count(); //amount is null if users are null.

Without the ? (the null-conditional operator) this call could throw a null pointer exception - given that users variable is null.

The above could also have been written like below:

int? amount;
if (users == null)
   amount = null;
else
   amount = users.Count();

So trading five lines of code for one is really neat. It could also have been written with a single line using ?: operator (ternary conditional operator):

var amount = users == null ? null : users.Count();

Still I believe the null-conditional operator is way more readable. As mentioned it can also be chained like the below.

var isDeveloper = users?[0].skills?.canDoProgramming? == E;

If any of the properties are null, isDeveloper will become null. But if everything is set it will contain a boolean value. The example above also contains a check on a specific index of the users collection. This is done by using a ? before [0]. It works the same way for collections as it does for fields.

I hope this helped you understand the null-conditional operator, please let me know in the comments down below if it did!