3

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?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • 1
    What would be the use to be able to do it ? overriding the + operator give the same result. – Franck Jun 07 '19 at 12:49
  • 8
    [RTFM](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/overloadable-operators): *"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."* – Sinatr Jun 07 '19 at 12:50
  • @Franck C++ programmers usually overload `operator+=` and then use it to overload `operator+`. Here's a tip from C++ Primer: "Classes that define both an arithmetic operator and the related compound assignment ordinarily ought to implement the arithmetic operator by using the compound assignment." – Aykhan Hagverdili Jun 07 '19 at 13:45
  • *I'm from C++ and using C# as newbie* -- Don't code C# using C++ as a model -- the slippery slope of writing code (or hoping to write code) in one language based on another language will creep in. All that will do is that persons versed in C# will find the code you wrote looks weird, different, and may have subtle bugs. The same vice-versa -- don't write C++ code using C# as a model. – PaulMcKenzie Jun 07 '19 at 21:23

1 Answers1

8

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.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325