C# class += operator overload

c#, oop, operator-overloading

Solution

From here you can't overload += directly but note the comment:

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded

So if you only overload the `+` operator that should be fine

Problem

I have a C# script that requires an item to be added or removed from a list. I thought it would be nicer to use += and -= operators. In C# an operator is done by: ``` public Foo operator +(Foo A, Foo B){ //Some adding code; return C; } ``` however I only get a syntax error when I attempt: ``` public SpriteValues operator +=(SpriteValues A){ //Add A to this return this; } ``` I know in python it would be done using: ``` def __iadd__(self, A): #Add A to this return self ``` So how do I do this in C#?

Original source