Where is the overload string + operator for string concatenation?

I recently thought about where string overloads the + operator. The only methods I see are == and != . Why can two lines be combined with +, even if this statement is not overloaded? Is this just a compiler magic trick or am I missing something? If the first, why was the string constructed in this way?

This question has been raised from this . It is difficult to explain to someone that he cannot use + to concatenate two objects, since object does not overload this operator if string does not care about operator overloading.

+5
source share
2 answers

The string does not overload the + operator. This is a C # compiler that converts a call to a + operator to a String.Concat method.

Consider the following code:

 void Main() { string s1 = ""; string s2 = ""; bool b1 = s1 == s2; string s3 = s1 + s2; } 

Produces 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 here. 7.7.4 The add statement , although it doesn't talk about calling String.Concat . We can assume that this is a detail of the implementation.

+8
source

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 execute the concatenation string. If the string concatenation operand is zero, the empty string is substituted. Otherwise, any non-string argument is converted to its string representation, calling the ToString virtual method inherited from the type object. If ToString returns null, the empty string is replaced.

I am not sure why the overload is mentioned, though .. Since we do not see any operator overloads.

+1
source

Source: https://habr.com/ru/post/1201634/


All Articles