Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# adding string + null doesn't throw an error?

Tags:

c#

As a programmer I would have expected this to throw an exception. Is there a reason why it treats null as ""?

string s = "hello";
string t = null;

Console.WriteLine(s + t);

Output:

hello

Just to emphasise my question, do you know why the decision to turn null into String.Empty was made? I was expecting some string to be added but there was a problem further back where it wasn't retrieving it properly and it came back with null. The problem went unnoticed!

Here's a pseudocode of why I think it is bad (and why I was shocked to discover no error):

You can assume I overloaded ToString to give the name of the person or details about them.

Person p = PersonDatabase.GetForName("Jimmy Gibbs");

Console.WriteLine("Name is: " + p.ToString());

Throws an exception because p is null

String p = PersonDatabase.GetForName("Jimmy Gibbs").Name;

Console.WriteLine("Name is: " + p);

Doesn't throw an exception, even though p is null (it treats it as "").

(If you want to be picky and say I won't be able to get Name as GetforName will be null, think of it as this:)

String p = PersonDatabase.GetNameFromID(1234); // Returns a string or null if not found

Console.WriteLine("Name is: " + p);

(If you use this value in a list or array you'll end up with a blank entry which is what broke for me, it was creating javascript and trying to get element by ID of "")

like image 994
NibblyPig Avatar asked Nov 17 '10 15:11

NibblyPig


1 Answers

From the C# Language Specification:

7.8.4 Addition operator

String concatenation:

string operator +(string x, string y); string operator +(string x, object y); string operator +(object x, string y);

These overloads of the binary + operator perform string concatenation. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

like image 186
Ani Avatar answered Oct 07 '22 21:10

Ani