Search code examples
c#.net

What's the difference between NotNullWhen(true) and MaybeNullWhen(false)


I'm a big fan of the try pattern in C#, particularly due to being able to use static analysis to add nullability hints via the [MaybeNullWhen] and/or [NotNullWhen] attributes.

What I don't understand is the difference between them, are they not the same given the opposite condition? As in:

bool MaybeNullWhen(false) NotNullWhen(true)
true not null not null
false might be null might be null

Is there a semantic difference that I'm missing?


Solution

  • There's a bit of history here.

    Nullable Reference Types, and those two attributes, were introduced in C# 8. However, the syntax T? (describing a generic type as "defaultable") was only introduced in C# 9.

    So when NRTs were introduced, you couldn't write this:

    public bool TryGetValue(TKey key, [NotNullWhen(true)] out TValue? value)
    

    Hence, the need for a different attribute.