5

I recently wondered where string overloads the +-operator. The only methods i can see are == and !=. Why can two strings be concatenated with + even if that operator is not overloaded? Is this just a magic compiler trick or am i missing something? If the former, why was string designed in that way?

This question was raised from this. It's difficult to explain someone that he cannot use + to concatenate two objects since object does not overload this operator if string does not care about overloading operators either.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Quite similar: [C# + operator calls string.concat function?](http://stackoverflow.com/questions/13617707/c-sharp-operator-calls-string-concat-function) – Soner Gönül Sep 02 '14 at 11:59
  • 1
    @SonerGönül: yes, now i've also found few questions like [this](http://stackoverflow.com/questions/10341188/string-concatenation-using-operator). I also wondered why i havent found a duplicate before i've asked this question. – Tim Schmelter Sep 02 '14 at 12:04
  • 2
    Concerning the why: Keep in mind that the CLR supports many languages. Some might not want to follow C#'s dubious decision to use `+` for string concatenation with arbitrary objects. – CodesInChaos Sep 02 '14 at 12:07

2 Answers2

9

String doesn't overload + operator. It is the c# compiler which converts the call to + operator to String.Concat method.

Consider the following code:

void Main()
{
    string s1 = "";
    string s2 = "";

    bool b1 = s1 == s2;
    string s3 = s1 + s2;
}

Produces the IL

IL_0001:  ldstr       ""
IL_0006:  stloc.0     // s1
IL_0007:  ldstr       ""
IL_000C:  stloc.1     // s2
IL_000D:  ldloc.0     // s1
IL_000E:  ldloc.1     // s2
IL_000F:  call        System.String.op_Equality //Call to operator
IL_0014:  stloc.2     // b1
IL_0015:  ldloc.0     // s1
IL_0016:  ldloc.1     // s2
IL_0017:  call        System.String.Concat // No operator call, Directly calls Concat
IL_001C:  stloc.3     // s3

Spec calls this out here 7.7.4 Addition operator, though it doesn't talks about call to String.Concat. We can assume it is implementation detail.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
1

This quote is from C# 5.0 Specification 7.8.4 Addition operator

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.

I'm not sure why is mentions about overloading though.. Since we don't see any operator overloads.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184