Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check for null parameters (Guard Clauses)

For example, you usually don't want parameters in a constructor to be null, so it's very normal to see some thing like

if (someArg == null) {     throw new ArgumentNullException(nameof(someArg)); }  if (otherArg == null) {     throw new ArgumentNullException(nameof(otherArg)); } 

It does clutter the code a bit.

Is there any way to check an argument of a list of arguments better than this?

Something like "check all of the arguments and throw an ArgumentNullException if any of them is null and that provides you with the arguments that were null.

By the way, regarding duplicate question claims, this is not about marking arguments with attributes or something that is built-in, but what some call it Guard Clauses to guarantee that an object receives initialized dependencies.

like image 589
SuperJMN Avatar asked Mar 21 '15 16:03

SuperJMN


Video Answer


1 Answers

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); 
like image 103
manuc66 Avatar answered Sep 23 '22 11:09

manuc66