Best way to check for null parameters (Guard Clauses)

With newer version of C# language you can write this without additional library or additional method call:

_ = someArg ?? throw new ArgumentNullException(nameof(someArg));
_ = otherArg ?? throw new ArgumentNullException(nameof(otherArg));

Starting from .NET6 you can also write this:

ArgumentNullException.ThrowIfNull(someArg);

Starting from .NET7 you can handle empty string and null checking:

ArgumentException.ThrowIfNullOrEmpty(someStringArg);

Leave a Comment