Why is adding null to a string legal?

The MSDN article on String Basics shows the following:

string str = "hello"; string nullStr = null; string emptyStr = ""; string tempStr = str + nullStr; // tempStr = "hello" bool b = (emptyStr == nullStr);// b = false; string newStr = emptyStr + nullStr; // creates a new empty string int len = nullStr.Length; // throws NullReferenceException 

Why not concatenation with an empty null exception? Make life easier for the programmer, so they don’t need to check for null before concatenation?

+49
c # language-design
Mar 12 '09 at 3:58
source share
5 answers

From MSDN :

In string concatenation operations, the C # compiler processes the empty string the same as the empty string, but it does not convert the value to the original empty string.

Additional information about + binary operator :

The binary + operator performs string concatenation when one or both operands are of type string.

If the string concatenation operand is null, the empty string is replaced. Otherwise, any non-string argument is converted to its string representation by calling the virtual ToString method inherited from the type object.

If ToString returns null, the empty string is replaced.

+50
Mar 12 '09 at 4:04
source share

I agree that conceptual strings are just meanings. However, consider the following code:

 int? i = null; i += 1; // The result of this is that i == null 

If other value type operators use default (), as string operators convert null to "", your explanation makes sense.

It’s easier to say that for convenience, line operators are shortcuts (a special case).

+6
Apr 28 '09 at 18:17
source share

Conceptually, strings are usually considered values, not references to objects that have an identity. One of the main reasons that they are not a struct with a semantics value is because of the overhead associated with copying at the destination. If the string values were , they could not be null, and therefore null processed only by the "+" operator, as if it were an empty string (ie. As default(string) == "" as default(int) == 0 )

+3
Mar 12 '09 at 4:31
source share

I suppose that the developers of the language (or the standard library) decided that this would be a fairly common case when they would benefit programmers.

(Neat! I always thought that concatenation with a null value would be thrown by an exception!)

+1
Mar 12 '09 at 4:08
source share

The reason that it does not throw the reference link exception is because you are not actually trying to access any properties or methods of the null object. As quoted by CMS, when concatenating strings, zeros are replaced by empty strings.

0
Mar 12 '09 at 4:08
source share



All Articles