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.
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.Stringin the CLI specification includes severalConcatoverloads, 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.Concatwhen compiling the+(string, string)operator.