5

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?

2
  • 1
    The + operator is a shorthand for the String.Concat method. If the arguments passed were null then it turns them into an empty string. Commented Aug 23, 2016 at 22:10
  • I have been programming in C#, C++, and C for many years and only just now discovered this today! In my head I was thinking string-concatenation would always yield null if all arguments were null. How have I never noticed this behavior before? I feel like such a newb now. Commented May 10, 2019 at 18:12

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good find, I could find it D=.
See more at Google Books
2

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.

4 Comments

For the downvote, look at ln 3002. =)
+ just uses the Concat method. stackoverflow.com/questions/10341188/…
@paqogomez nice thank you, ill check out that SO question.
Thank you for clarify. Unfortunately I only can chose one answer, but I upvoted both. Living and learning!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.