简体   繁体   中英

Why can't a nullable int as string be null in 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! :)

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
    }

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.

    int? i = null;

    var str = i.ToString();

    int? j = null;

    var str2 = j?.ToString();

In the above code, str will be the empty string and str2 will be null. By using the ?. operator on j, we can get a null value instead of the empty string for str2. This is a workaround that provides a more intuitive string conversion and would make the OP code reachable.

.ToString() cannot allow null value.

You can use:

 convert.ToString(newInt)

Check condition by:

 "string.IsNullOrEmpty(test))"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM