Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# + operator calls string.concat function? [duplicate]

Possible Duplicate:
Does C# optimize the concatenation of string literals?

I just found out that we write a line like this:

string s = "string";
s = s + s; // this translates to s = string.concat("string", "string");

However I opened the string class through reflector and I don't see where this + operator is overloaded? I can see that == and != are overloaded.

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool operator ==(string a, string b)
    {
      return string.Equals(a, b);
    }
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool operator !=(string a, string b)
    {
      return !string.Equals(a, b);
    }

So why does concat gets called when we use + for combining strings?

Thanks.

like image 400
Varun Sharma Avatar asked Nov 29 '12 02:11

Varun Sharma


2 Answers

So why does concat gets called when we use + for combining strings?

Section 7.7.4 of the C# specification, "Addition operator", defines a binary addition operator for strings, where the operator returns the concatenation of the operands.

The definition of System.String in the CLI specification includes several Concat overloads, but no + operator. (I don't have a definitive answer explaining that omission, but I suppose it's because some languages define operators other than + for string concatenation.)

Given these two facts, the most logical solution for the C# compiler writer is to emit a call to String.Concat when compiling the +(string, string) operator.

like image 89
phoog Avatar answered Sep 25 '22 14:09

phoog


The code

    public string Foo(string str1, string str2)
    {
        return str1 + str2;
    }

gives the following IL:

IL_0000:  nop
IL_0001:  ldarg.1
IL_0002:  ldarg.2
IL_0003:  call       string [mscorlib]System.String::Concat(string, string)
IL_0008:  stloc.0
IL_0009:  br.s       IL_000b
IL_000b:  ldloc.0
IL_000c:  ret

The compiler (at least, the one in Visual Studio 2010) does this job and there is no + overloading.

like image 29
Guillaume Avatar answered Sep 25 '22 14:09

Guillaume