Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading