Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a nullable int as string be null in c#?

Tags:

c#

For some reason unknown visualstudio tells me this code is unreachable:

            int? newInt = null;
            string test = newInt.ToString();
            if (test == null)
            {
                //unreachable Code
            }

Thank you for your help! :)

like image 771
LuSt Avatar asked Jan 04 '23 16:01

LuSt


2 Answers

string test = newInt.ToString();

test will never be null if you convert it to string. when you convert it, it will become empty string.

int? newInt = null;
string test = newInt.ToString();
if (test == "")
    {
        Console.WriteLine("Hello World"); //Reaches the code
    }
like image 185
Prajwal Avatar answered Jan 15 '23 00:01

Prajwal


Because:

((int?)null).ToString() == string.Empty

The return value from a nullable int is an empty string. The code in the if block is indeed checking for a null value that could never exist. This only works because int? is a framework type, and the behaviour of ToString() is known and immutable. If you tried this on a user-defined value type, the same assertion could not be made.

like image 23
richzilla Avatar answered Jan 14 '23 22:01

richzilla