Search code examples
c#nullablestatic-analysisnon-nullable

C# Compiler's null state static analysis when validating objects


I have enabled Nullable check in my project and in a lot of places in the code I check input object and its properties and throw exception if something is wrong. But if everything is all right then I'm certain that input object is not null. Is there a way to tell this to compiler, to somehow use NotNullWhen attribute or something like that? I don't want to disable nullable check anywhere in the code.

void Validate(MyClass1? obj1, MyClass2 obj2)
{
    if (obj1 == null || obj2 == null)
    {
        throw new ArgumentNullException();
    }
}

void DoSomething(MyClass1 obj1, MyClass2 obj2)
{
    // This method requires not-null objects
    ...
}

void Process(MyClass1? obj1, MyClass2 obj2)
{
    Validate(obj1, obj2);
    
    // this produces warning, requires to explicitly check if both objects are not null
    DoSomething(ob1, obj2);
}

Solution

  • You can use NotNullAttribute from System.Diagnostics.CodeAnalysis namespace:

    Specifies that an output is not null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.

    void Validate([NotNull] MyClass1? obj1, [NotNull] MyClass2 obj2)
    {
        ...
    }
    

    Also this article can be helpful too.