Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is adding null to a string legal?

The MSDN article on String Basics shows this:

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 doesn't concatenating with null throw a null reference exception? Is it to make a programmer's life easier, such that they don't have to check for null before concatenation?

like image 662
David Hodgson Avatar asked Mar 12 '09 03:03

David Hodgson


People also ask

What happens if you add null to a string?

If the input object is null, it returns an empty (“”) String, otherwise, it returns the same String: return value == null ? "" : value; However, as we know, String objects are immutable in Java.

Why use null instead of empty string?

NULL is used in SQL to indicate that a value doesn't exist in the database. It's not to be confused with an empty string or a zero value. While NULL indicates the absence of a value, the empty string and zero both represent actual values.

Is null valid string?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.

Can we set null to string?

null is not a special string value (there's String. Empty for "" ), but a general object literal for the empty reference.


1 Answers

From MSDN:

In string concatenation operations, the C# compiler treats a null string the same as an empty string, but it does not convert the value of the original null string.

More information on the + binary operator:

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

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 178
Christian C. Salvadó Avatar answered Sep 22 '22 11:09

Christian C. Salvadó