6

Possible Duplicate:
Why must we define both == and != in C#?

Why is overloading of += possible only by overloading of +, but == and != are separately overloaded?
It seems it should be inverted.
+= overloading is nearly always possible to write more effective because it's unnecessary to allocate memory for new object. But I can't invent an example in which operators == and != should be different in something except inverting the result Equals().

Community
  • 1
  • 1
Nelson Tatius
  • 7,693
  • 8
  • 47
  • 70

1 Answers1

7

A similar question has been asked before.

The biggest reason is that when you overload the == and != operators, you don't have to return a boolean. If you're not returning a boolean, you can't just invert the complimentary operator. There are other possible reasons they are separately overloaded, you can view the answers to that question for those other reasons.

There is a valid reason you can't overload += and therefore it is done implicitly via the + operator. I has to do with the fact that you can't override the assignment operator in C#, it's part of the language standard. The += is increment and assign, the latter of which you can't overload in C#.

Community
  • 1
  • 1
Christopher Currens
  • 29,917
  • 5
  • 57
  • 77
  • 4
    +1 Just imagine the craziness if you could overload `+` and `+=` separately... – Chris Laplante Aug 16 '11 at 17:43
  • If C# and .net didn't do evil things with mutable structures (mutable structs aren't evil--some things .net does with them are), or if they allowed classes to restrict the evil promiscuous sharing of references to their objects, it would be useful to have separate += and + operators, since using the "+" operator would imply making a copy and leaving the original untouched, whereas "+=" implies the original can be modified. Note, btw, that events support "+=" and "-=", but do not support "+" and "-". – supercat Sep 16 '11 at 22:00