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.
Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows.
Overloaded Operators in the string classString comparison ( == , != , > , < , >= , <= ): For example, you can use str1 == str2 to compare the contents of two string objects. Stream insertion and extraction ( << , >> ): For example, you can use cout << str1 and cin >> str2 to output/input string objects.
In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With