Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why concatenating two null string results an empty string? [duplicate]

I just saw a weird result while I tried to concatenate two null strings: it returns an empty one! I can not imagine if it have some utility or why this occurs.

Example:

string sns = null;
sns = sns + sns;
// It results in a String.Empty

string snss = null;
snss = String.Concat(snss, snss);
// It results in a String.Empty too!

Can someone tell me why it returns a String.Empty instead of null?

like image 229
Striter Alfa Avatar asked Aug 23 '16 21:08

Striter Alfa


People also ask

What is the result when two NULL strings are concatenated?

Using the String. concat() method is a good choice when we want to concatenate String objects. The empty String returned by the getNonNullString() method gets concatenated to the result, thus ignoring the null objects.

Why concatenation with empty set is empty?

However, performing a concatenation with the empty set results in an empty set. This is because one half of the result needs to come from an element of the empty set of which there are none.

What happens when you concatenate NULL?

When SET CONCAT_NULL_YIELDS_NULL is ON, concatenating a null value with a string yields a NULL result. For example, SELECT 'abc' + NULL yields NULL .

What happens when two strings are concatenated?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.


2 Answers

Here is a fragment from C# Language Specification, the “7.8.4 Addition operator” section:

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 136
AndreyAkinshin Avatar answered Nov 06 '22 02:11

AndreyAkinshin


http://referencesource.microsoft.com/#mscorlib/system/string.cs

If the string is null, it returns String.Empty.

As for the operator +, I am not too sure.

like image 2
TheNoob Avatar answered Nov 06 '22 01:11

TheNoob