kofifus
kofifus

Reputation: 19276

Incorrect warning Converting null literal or possible null value to non-nullable type

I try:

var err = (string)null;

(which I prefer to string? err=null;)


I get

warning CS8600: Converting null literal or possible null value to non-nullable type.

But the type of err is correctly set to a nullable string as is evident by hovering over it in visual studio.

Is this warning a dud ?

Upvotes: 0

Views: 9913

Answers (1)

Sweeper
Sweeper

Reputation: 270758

Assuming you have nullable reference types turned on, the warning is correctly pointing out that you are casting null to a non-nullable type - string. It is not about the type of err being non-nullable. err is nullable, as vars always are.

If you cast to string? instead, which is nullable, then the warning goes away:

var err = (string?)null;

Upvotes: 6

Related Questions