Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# class += operator overload

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#?

like image 442
Jonathan Avatar asked Apr 22 '26 10:04

Jonathan


2 Answers

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

like image 174
nkvu Avatar answered Apr 24 '26 23:04

nkvu


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.

like image 39
Daniel Imms Avatar answered Apr 24 '26 22:04

Daniel Imms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!