1

I have a code concatenating two string using plus operator. If two strings are null, sum of two strings is not null.

var strLeft = default(string);
var strRight = default(string);

var strSum = strLeft + strRight;

I want to distinguish String.Empty + default(string) and default(string) + default(string). Both concat operation result is String.Empty.

Why results of both total are String.Empty?

selami
  • 2,478
  • 1
  • 21
  • 25

2 Answers2

4

The + operator calls on string arguments are translated by the C# compiler to calls to the string.Concat method. And here's what the documentation of this method states:

An Empty string is used in place of any null argument.

So basically that's by design. The string.Concat method will never return null.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Emphasis: the `+` is handled by the compiler and this is not something you could achieve for your own class by overloading `operator+` – H H Feb 16 '14 at 14:58
  • Yes, precisely. That's what I mentioned in my first sentence. The `+` operator is translated by the C# compiler to calls to the string.Concat method. – Darin Dimitrov Feb 16 '14 at 14:58
1

It's because null string is treated as empty string 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

dkozl
  • 32,814
  • 8
  • 87
  • 89