Checking for nulls is one of those things that leads to a lot of boilerplate code in C#. As such, I want it to take up as little space as possible so it doesn't distract me from the "real" code.
Here's my current favorite one-liner way of doing it.
_ = myArg ?? throw new ArgumentNullException(nameof(myArg));
This makes use of discards (
_) and the null-coalescing operator (
Discards are placeholder variables that are intentionally left unused.
The null-coalescing operator returns the value on the left side if it isn't null, otherwise it returns the result of the operand on the right side.
In other words, all we're doing here is placing the value of
myArg in an unused variable if it's not null, and when it is null, we throw an error instead.
You could argue that this code is a little weird and not quite as readable as using a full if statement instead, but I think that's a trade-off worth doing in this case.
By the way, there's an even better way of checking for nulls on the horizon. A feature called "Simplified Null Argument Checking" may be coming in a future release of C# (it was removed from C# 9 at a late stage). If added, all you have to do is put
! at the end of a parameter name and it will run the same code as above under the hood.