Best way to check for null parameters (Guard Clauses)

43,401

Solution 1

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);

Solution 2

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 ContractAnnotationAttribute makes sure that I never misspell the argument ("foo") and also renames it automatically if I rename the foo symbol.
  • The NotNullAttribute helps ReSharper with code analysis. So if I do new 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 3

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 4

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 5

Ardalis has an excellent GuardClauses library.

It's nice to use Guard.Against.Null(message, nameof(message));

Share:
43,401

Related videos on Youtube

SuperJMN
Author by

SuperJMN

De ve lo per

Updated on February 12, 2022

Comments

  • SuperJMN
    SuperJMN over 2 years

    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.

    • Alex Shesterov
      Alex Shesterov over 9 years
    • JoJo
      JoJo over 9 years
      maybe put them all in an object array and iterate over them using a foreach loop? you need something like that?
    • Andre
      Andre over 9 years
      We usually check our parameters at the beginning of the method like your code snippet. Not only for null, also for other business logic behaviors. I don't see any problem with that as long as you don't have too many parameters. At least you can read the requirements of your method easily.
    • Daniel Mann
      Daniel Mann over 9 years
      @JoJo That's an awful idea. You don't want to make a method that is intended to take a very specific number and type of objects as parameters take an unknown number of objects of unknown types just for the sake of easily checking if they're null. You're solving one problem by creating a much bigger problem.
    • JoJo
      JoJo over 9 years
      @DanielMann well what could you do else to make it shorter? i was just giving an example
  • Daniel Smith
    Daniel Smith almost 8 years
    Just a minor note, you could also use the nameof operator instead of hard coding the argument name, e.g. Guard.ThrowIfNull(obj, nameof(obj))
  • Toby Speight
    Toby Speight about 6 years
    Am I right in thinking that all arguments are evaluated, even when the condition is false? That's not a problem for the simple cases in the question, but something users would want to be aware of when using this library in other contexts.
  • Hennadii
    Hennadii about 6 years
    Each argument should have separate check. I.e. for the case in the question it would be as below: Throw.ArgumentNullException(when: someArg.IsNull(), nameof(someArg)); Throw.ArgumentNullException(when: otherArg.IsNull(), nameof(otherArg)); If evaluation of the first expression someArg.IsNull() is true, then the exception is thrown, so the second expression otherArg.IsNull() is not evaluated etc.
  • Toby Speight
    Toby Speight about 6 years
    What I mean is than nameof(someArg) is always evaluated, even if someArg.IsNull() returns false, unlike the if/then construct. In this case, that's probably okay, but may be undesirable if instead of a simple nameof() we had something with side effects (including timing effects).
  • Hennadii
    Hennadii about 6 years
    Right. That's why throwing of exceptions should be like a simple single-line expression. If there is some i.e. multi-line logic, especially with side effects, it is better to use regular if statement because that logic would be more readable (as for me, i'd consider it as part of your agorithm)
  • Alexcei Shmakov
    Alexcei Shmakov about 5 years
    do you know about how to rewrite this code to Code Contract instead ResharperAnnotation. Is it even possible? Or I didn't understand. In advance Thank you for any helps
  • Erusso87
    Erusso87 about 5 years
    Code contracts are basically dead. I wouldn’t use them anymore. If you are on .NET Core or plan to switch to it, I would use the new nullable reference types feature.
  • Daniel
    Daniel about 4 years
    In case you haven't encountered discards yet and like me are wondering about the underscore.
  • aufty
    aufty about 4 years
    @DanielSmith any reason to not move the nameof(obj) to inside of the ThrowIfNull method and only have one argument while you're at it?
  • Vector Sigma
    Vector Sigma about 4 years
    @aufty because nameof(obj) just returns "obj". What Daniel meant there was nameof(howeverYourParameterIsNamed). In ThrowIfNull, you have to write nameof(argumentValue) (or however you choose to name the parameter), so you will always get NullReferenceException: argumentValue was null... not very enlightening.
  • Matt
    Matt almost 4 years
    I agree with what you said here but I don't see how I can apply it to the stated problem in order disallow nulls at compile time because reference types in c# are always nullable.
  • Zoran Horvat
    Zoran Horvat almost 4 years
    @TimAbell OP didn't ask for that; anyway C# 8 is now introducing nullable reference types, so that you can force the compiler report all suspicious accesses to references that may be null. Other possibility is to rely on optional objects, which are not supported by C# natively.
  • Konard
    Konard almost 3 years
    At the LinksPlatform we have Platform.Exceptions library that contains a similar implementation of single line checkers methods. If you need additional checks, you can either extend our implementation with extension methods or ask us to add these checks into our library.
  • user2315856
    user2315856 over 2 years
    Newer shorter way with upcoming .NET6: ArgumentNullException.ThrowIfNull(someArg); (stackoverflow.com/a/69836300/2315856)
  • Aleksei Mialkin
    Aleksei Mialkin over 2 years
    Seems like this feature with !! never made it to C# 10.