Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 521
Jonathan Wood Avatar asked Mar 03 '26 20:03

Jonathan Wood


2 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.

like image 131
pfx Avatar answered Mar 06 '26 03:03

pfx


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!

like image 29
José Alvarez Avatar answered Mar 06 '26 01:03

José Alvarez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!