Possible null reference assignment warning seems bogus to me

Viewed 2068

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

3 Answers

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.

You can use AllowNullAttribute class which:

Specifies that null is allowed as an input even if the corresponding type disallows it.

for example:

[AllowNullAttribute]
public string Host

This way you wont get those annoying warnings!

string? is already declared, intellisence will definitly take it into nullable value on some cases.

Related