C# operator overloading, where is my +=?November 27, 2006 at 10:02 am | Posted in C#, Programming | 24 Comments
Coming from a C++ background, I never understood why they left out operator overloading in Java. Sure it can lead to obscure code in the hands of incompetent programmers, but I guess the same goes with cars and incompetent drivers. That can (and does) cause some problems, but I’ve never heard of people proposing to ban all cars so that this relatively small group doesn’t cause any harm any more.
Today I don’t want to solve the problem of incompetent programmers. Today I just want to complain about not being able to overload the += operator in C#. Why is this a problem? As you all know all C# overloading operators need to be defined as public and static. So if you add 2 objects, for example 2 Pixel objects in my GIMP# code, you have to allocate a new Pixel, do your math, and return this new object. This is all done by overloading the + operator: public static operator + (Pixel p1, Pixel p2).
So far, so good. Now in C++ I would add a non-static operator += that simply adds the Pixel parameter to the current instance of my Pixel object. No need to allocate a new Pixel, since I already have it (the implicit this object). In C# I get the += operator “for free”. The downside obviously is that this so-called free method still allocates a new Pixel object before assigning it to my current object This wouldn’t be so bad if the language would allow me to overload the += operator but this is not possible. Only alternative I have at the moment is to define a Pixel.Add(Pixel p) method, but what’s the point of operator overloading in that case.
Ah well, maybe this shortcoming will be fixed in a future version. I hope someone can tell me what the rationale was behind this design decision.