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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With