Search code examples
c#.net-corenullable-reference-types

Cannot fix nullable warning with ternary - .NET


The following code produces a warning,

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

int? a = 1;
string lineCount = a != null ? a.ToString() : string.Empty;

It appears that it is because ToString() returns string?. However, even casting that to string doesn't remove the warning.

string lineCount = a != null ? (string)a.ToString() : string.Empty;

However, if the integer is not nullable, it does not produce this warning.

How can I get rid of this warning?


Solution

  • There are two solutions to this.

    Firstly, you can make sure you call ToString() on the int, not the Nullable<int>:

    int? a = 1;
    string lineCount = a != null ? a.Value.ToString() : string.Empty;
    

    Note the use of a.Value here. That way, the compiler knows you're calling it on an int, and as you said in the question, the compiler knows that int.ToString() never returns null. (It's declared to return string, not string?... whereas Nullable<T>.ToString() is still declared to return string?.)

    A variant on this approach is to use pattern matching to capture the non-nullable integer:

    int? a = 1;
    string lineCount = a is int value ? value.ToString() : string.Empty;
    

    The second approach would be to use the null-conditional operator in conjunction with the null coalescing operator:

    int? a = 1;
    string lineCount = a?.ToString() ?? string.Empty;
    

    Personally I'd use that as a simpler approach.