'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.
Solution 1:[1]
public static class Ensure
{
/// <summary>
/// Ensures that the specified argument is not null.
/// </summary>
/// <param name="argumentName">Name of the argument.</param>
/// <param name="argument">The argument.</param>
[DebuggerStepThrough]
[ContractAnnotation("halt <= argument:null")]
public static void ArgumentNotNull(object argument, [InvokerParameterName] string argumentName)
{
if (argument == null)
{
throw new ArgumentNullException(argumentName);
}
}
}
usage:
// C# < 6
public Constructor([NotNull] object foo)
{
Ensure.ArgumentNotNull(foo, "foo");
...
}
// C# >= 6
public Constructor([NotNull] object bar)
{
Ensure.ArgumentNotNull(bar, nameof(bar));
...
}
The DebuggerStepThroughAttribute comes in quite handy so that in case of an exception while debugging (or when I attach the debugger after the exception occurred) I will not end up inside the ArgumentNotNull method but instead at the calling method where the null reference actually happened.
I am using ReSharper Contract Annotations.
- The
ContractAnnotationAttributemakes sure that I never misspell the argument ("foo") and also renames it automatically if I rename thefoosymbol. - The
NotNullAttributehelps ReSharper with code analysis. So if I donew Constructor(null)I will get a warning from ReSharper that this will lead to an exception. - If you do not like to annotate your code directly, you can also do the same thing with external XML-files that you could deploy with your library and that users can optionally reference in their ReSharper.
Solution 2:[2]
If you have too many parameters in your constructors, you'd better revise them, but that's another story.
To decrease boilerplate validation code many guys write Guard utility classes like this:
public static class Guard
{
public static void ThrowIfNull(object argumentValue, string argumentName)
{
if (argumentValue == null)
{
throw new ArgumentNullException(argumentName);
}
}
// other validation methods
}
(You can add other validation methods that might be necessary to that Guard class).
Thus it only takes one line of code to validate a parameter:
private static void Foo(object obj)
{
Guard.ThrowIfNull(obj, "obj");
}
Solution 3:[3]
Null references are one sort of troubles you have to guard against. But, they are not the only one. The problem is wider than that, and it boils down to this: Method accepts instances of a certain type, but it cannot handle all instances.
In other words, domain of the method is larger than the set of values it handles. Guard clauses are then used to assert that actual parameter does not fall into that "gray zone" of the method's domain which cannot be handled.
Now, we have null references, as a value which is typically outside the acceptable set of values. On the other hand, it often happens that some non-null elements of the set are also unacceptable (e.g. empty string).
In that case, it may turn out that the method signature is too broad, which then indicates a design problem. That may lead to a redesign, e.g. defining a subtype, typically a derived interface, which restricts domain of the method and makes some of the guard clauses disappear. You can find an example in this article: Why do We Need Guard Clauses?
Solution 4:[4]
Ardalis has an excellent GuardClauses library.
It's nice to use Guard.Against.Null(message, nameof(message));
Solution 5:[5]
In C# 8.0 and later, new helps are available. C# 8.0 introduces non-nullable reference types (a feature somewhat confusingly called "nullable reference types" in the docs). Prior to C# 8.0, all reference types could be set to null. But now with C# 8.0 and the 'nullable' project setting, we can say that reference types are by default non-nullable, and then make our variables and parameters nullable on a case-by-case basis.
So whereas at the moment, we recognize code like this:
public void MyFunction(int thisCannotBeNull, int? thisCouldBeNull)
{
// no need for checking my thisCannotBeNull parameter for null here
}
If you set <Nullable>enable</Nullable> for your C# v8.0+ project, you can do things like this too:
public void MyFunction(MyClass thisCannotBeNull, MyClass? thisCouldBeNull)
{
// static code analysis at compile time checks to see if thisCannotBeNull could be null
}
The null-checking is done at compile-time, using static code analysis. So if you've coded it in a way that means a null could turn up there, you'll get a compiler warning (which you can upgrade to an error if you want). So lots (but not all) of the situations where you need a run-time check for null parameters can be handled as a compile-time check based on your code.
Solution 6:[6]
C# 11 introduces the shortest way to do this (by far). You need only 2 exclamation marks !! right after the argument(s) you want to check for null.
Before:
public void test(string someArg){
if (someArg == null)
{
throw new ArgumentNullException(nameof(someArg));
}
// other code
}
With C# 11 or higher:
public void test(string someArg!!){
// other code
}
If you call test(null), an ArgumentNullException will be thrown telling you that someArg is null.
Microsoft mentioned it in early 2021, but it did not become part of C# 10: A video on the 'Microsoft Developer' YouTube channel explaining the new feature.
The feature was implemented in February 2022, see on GitHub.
Please note: It's a C# 11 feature and C# 11 isn't officially released yet. It will probably be released with .Net7 in November 2022.
Solution 7:[7]
With newer newer version of C# (C# 10, .NET6 will be released in a few days) you can even do:
ArgumentNullException.ThrowIfNull(someArg);
Doc: https://docs.microsoft.com/en-us/dotnet/api/system.argumentnullexception.throwifnull?view=net-6.0
Solution 8:[8]
You might try my Heleonix.Guard library, which provides guard functionality.
You can write guard clauses like below:
// C# 7.2+: Non-Trailing named arguments
Throw.ArgumentNullException(when: param.IsNull(), nameof(param));
// OR
// Prior to C# 7.2: You can use a helper method 'When'
Throw.ArgumentNullException(When(param.IsNull()), nameof(param));
// OR
Throw.ArgumentNullException(param == null, nameof(param));
// OR
Throw.ArgumentNullException(When (param == null), nameof(param));
It provides throwing of many existing exceptions, and you can write custom extension methods for custom exceptions. Also, the library refers to the 'Heleonix.Extensions' library with predicative extensions like IsNull, IsNullOrEmptyOrWhitespace, IsLessThan and many more to check your arguments or variables against desired values. Unlike some other guard libraries with fluent interfaces, these extensions do not generate intermediate objects, and since implementation is really straightforward, they are performant.
Solution 9:[9]
If you want to save typing the argument name twice, like Guard.AgainstNull(arg, nameof(arg));
check out YAGuard, where you can write Guard.AgainstNull(arg);
No need to specify the name of the argument in the guard clause, but in the argument thrown, the name is correctly resolved.
It also supports guard-and-set in the form MyProperty = Assign.IfNotNull(arg);
Nuget: YAGuard
Disclaimer: I'm the author of YAGuard.
Solution 10:[10]
The simplest approach I've found is inspired by Dapper's use of anonymous types. I've written a Guard class that uses anonymous types to get name of properties. The guard itself is the following
public class Guard
{
public static void ThrowIfNull(object param)
{
var props = param.GetType().GetProperties();
foreach (var prop in props)
{
var name = prop.Name;
var val = prop.GetValue(param, null);
_ = val ?? throw new ArgumentNullException(name);
}
}
}
You then use it like so
...
public void Method(string someValue, string otherValue)
{
Guard.ThrowIfNull(new { someValue, otherValue });
}
...
When the ArgumentNullException is thrown, reflection is used to determine the name of the property which will then be displayed in your exception
Solution 11:[11]
There is a nuget package called SwissKnife. Install SwissKnife from nuget gallery. It provides you with many options starting with null checking for arguments
Argument.IsNotNullOrEmpty(args,"args") under SwissKnife.Diagnostics.Contracts namespace alongwith with option idoim and many more. You can set Option<Class_Name> _someVar and then check if _someVar.IsSome or _someVar.IsNone. This helps against nullable classes as well. Hope this helps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
