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#?
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
You can't overload the += operator as a += b it is just shorthand for a = a + b.
Overloading the + operator will allow you to use += on your object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With