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

You probably ended up here because you want to avoid nested if statements or found a ? symbol in a codebase, that you did not understand. Perhaps you are just looking for an easy way to do null checks. From C# 6 and on there is the Null-Conditional operator. The null-conditional operator is only for readability. It is simply sugar syntax making your code easier to read and comprehend. Of course this is only so, if you understand what it does! It is simply a way to make null checks in an easy and chainable way. Which reduces 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 is null.

Without the ? (the null-conditional operator) this call could throw a nullpointer 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 5 lines of code for 1 is really neat. It could of course also have been written with a single line using ?: 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.