The System.String has only two Operator overloaded
public static bool operator ==(string a, string b)
{
return string.Equals(a, b);
}
public static bool operator !=(string a, string b)
{
return !string.Equals(a, b);
}
But when using += for String concat, Example :
private static void Main()
{
String str = "Hello ";
str += "World";
Console.WriteLine(str);
}
it works just fine,
So, how come if System.String doesn’t overload the operator += it Concats the string?
First, the operator
+=can’t be overloaded. If you have the expressionA += B, it’s compiled as if you wrote:*Okay, that’s why
stringdoesn’t overloadoperator +=(because it can’t be overloaded). So, why doesn’t it overloadoperator +either? It’s just one more difference between the CLR and C#. The C# compiler knows that types likestringandintare special, and it generates special code for their operators (callingstring.Concat()forstring, or theaddinstruction forint).Why are these operators treated in a special way? Because you want them treated in a special way. I think this is most clear for
int:intaddition to be compiled as a method call, that would add a lot of overhead. Because of that, special instruction forintaddition is used.checkedanduncheckedoperators. How should the compiler deal with that if it had onlyoperator +? (What it actually does is to use the instructionaddfor unchecked overflows andadd.ovffor checked overflows.)And you want to treat
stringaddition in a special way too, for performance reasons. For example, if you havestringsa,bandcand writea + b + cand then you compiled that as two calls tooperator +, you would need to allocate a temporarystringfor the result ofa + b, which is inefficient. Instead, the compiler generates that code asstring.Concat(a, b, c), which can directly allocate only one string of the required length.* This is not exactly right, for details, see Eric Lippert’s article Compound Assignment, Part One and Compound assignment in the C# specification. Also note the missing semicolons,
A += Breally is an expression, for example, you can writeX += Y += Z;.