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?

Akira Yamamoto
  • 4,685
  • 4
  • 42
  • 43
Striter Alfa
  • 1,577
  • 1
  • 14
  • 31
  • 1
    The `+` operator is a shorthand for the [`String.Concat`](https://msdn.microsoft.com/en-us/library/a6d350wd(v=vs.110).aspx) method. If the arguments passed were `null` then it turns them into an empty string. – Raktim Biswas Aug 23 '16 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. – MikeTeeVee May 10 '19 at 18:12

2 Answers2

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.

poke
  • 369,085
  • 72
  • 557
  • 602
AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155
  • Good find, I could find it D=. – TheNoob Aug 23 '16 at 22:04
  • See more at [Google Books](https://books.google.com.br/books?id=s-IH_x6ytuQC&lpg=PT432&ots=lsc19Y7M6V&dq=%E2%80%9C7.8.4%20Addition%20operator%E2%80%9D&hl=pt-BR&pg=PT433#v=onepage&q=%E2%80%9C7.8.4%20Addition%20operator%E2%80%9D&f=false) – Akira Yamamoto Aug 23 '16 at 22:08
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.

TheNoob
  • 861
  • 2
  • 11
  • 25