Does C# operator overloading support "+=" like C++?

Viewed 409

I'm from C++ and using C# as newbie, just tried this out:

class Class1
{
    int mI = 0;
    string mS = "ab";

    public static Class1 operator + (Class1 obj1, Class1 obj2)
    {
        return new Class1()
        {
            mI = obj1.mI + obj2.mI,
            mS = obj1.mS + obj2.mS
        };
    }

    public static void operator += (Class1 obj1)
    {
        mI += obj1.mI;
        mS += obj1.mS;
    }
}

I found that operator+= function doesn't compile, saying:

error CS1019: Overloadable unary operator expected.

So C# doesn't do this kind of operator overloading at all?

1 Answers

You can overload +, but not +=, as per the documentation:

Assignment operators cannot be explicitly overloaded. However, when you overload a binary operator, the corresponding assignment operator, if any, is also implicitly overloaded. For example, += is evaluated using +, which can be overloaded.

So, as you can read, += is considered x = x + y. That's why it is not allowed to overload the += operator.

Related