C#10 unclear CS8600 warning

Viewed 7579

I'm currently migrating a Blazor project to .NET6 which comes with C# 10. With the new language version I'm getting a warning with the following code:

if (tmp is null)
    oldValue = "";
else
    oldValue = tmp.ToString();

The warning is: CS8600 "Converting null literal or possible null value to non-nullable type". tmp is of type object?. That is the reason why I'm checking if it is null in the if clause. I have noticed that many warnings of this type occur.

So what is the reason behind that? The Help page does not contain any information yet. (see here)

3 Answers

It appears that CS8600 warning is thrown when the compiler is not sure if the type is nullable or not. If you cast oldValue = (string?) tmp; the compiler is happy and the warning goes away.

you have to cast to non nullable, like this

    int? tmp = 0;
    string oldValue;

    oldValue = tmp == null ? "" : ((int)tmp).ToString();

or using your syntax

    if (tmp is null)
        oldValue = "";
    else
        oldValue = ((int) tmp).ToString();

I assume the problem here is the type of oldValue, which is not visible in the code. If it is also of type object, make it a nullable object instead:

object? oldValue;
Related