Search code examples
c#.net-5nullablenullable-reference-types

Possible null reference assignment warning seems bogus to me


The following code is giving me a warning but I don't understand why.

client.Host = Settings.Host;

warning CS8601: Possible null reference assignment.

Both client and Settings are not null here. And both client.Host and Settings.Host are of type string?.

Therefore, while it could be a possible null reference assignment, it shouldn't matter because the target variable allows null.

client.Host may be null

Settings.Host may be null


Solution

  • Notice the DisallowNull attribute on the Host property declaration.

    From the documentation

    Specifies that null is disallowed as an input even if the corresponding type allows it.

    [DisallowNull]
    public string? Host
    

    Since it is declared in the System.Diagnostics.CodeAnalysis namespace, Visual Studios code analyzer will take this into account.