Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does does this implicit use of ToString() not cause an exception?

Tags:

c#

.net

I've created a trivial example with which to ask this question.

The following code compiles and runs:

static void Main(string[] args)
{
    string bigString, littleString;
    littleString = null;
    bigString = "word " + littleString + " word";
}

This code compiles but throws a runtime NullReference exception.

static void Main(string[] args)
{
    string bigString, littleString;
    littleString = null;
    bigString = "word " + littleString.ToString() + " word";
}

Why does the first code not throw a similar exception? I would have thought that in order to concatenate it to the other strings that there would be an implicit use of ToString(), at which point it would run into the same fundamental problem as the second piece of code.

like image 322
Sperick Avatar asked Feb 04 '26 00:02

Sperick


1 Answers

The first snippet doesn't call ToString at all. It calls string.Concat(string, string) which in its implementation, handles null values as if they were empty strings. It doesn't need to call ToString to convert that argument to a string (whether it's null or not) because it is already a string. (If it weren't a string, then it would need to call ToString on it, but it would only do so if it is not null).

like image 78
Servy Avatar answered Feb 05 '26 13:02

Servy