System.String does not overload the + = operator But String Concatenation works, How?

There are only two overloaded operators in System.String.

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 fine

So how does it turn out if System.String does not overload the + = it operator Concatenates a string?

+5
source share
4 answers

Firstly, the operator +=cannot be overloaded. If you have an expression A += B, it compiles as if you wrote: *

A = A + B

, string operator += ( ). operator +? CLR #. # , , string int, , ( string.Concat() string add int).

? , . , int:

  1. , int , . - int.
  2. . , , checked unchecked. , operator +? ( add add.ovf .)

string . , string a, b c a + b + c, operator +, string a + b, . string.Concat(a, b, c), .


* , . , #. , A += B , , X += Y += Z;.

+8

+=, var = var + newValue. .

+ = ( #)

+ = , +

:

string str = "new string";
str += "new value";

:

str = str + "new value";

string.Concat .

+5

+= not explicitly implemented, but it works because the compiler does this magic

str += "World";

str =  str + "World";

str = str.Concat("World");
+3
source

As the above guys said, and according to .NET, is string += otherStringequivalent

string = string + otherString

This .NET link mentions the concatenation operator and this.NET link talks about the relationship between the two operations.

0
source

All Articles