views:

359

answers:

5

why c# not allowed operator overloading while C++ do?

I got this error, when trying to overload.

Overloadable binary operator expected

My sample code looks like,

public static MyClass operator +=(MyClass obj1, MyClass obj2)
        {
           ...
        }
+2  A: 

c# does allow operator overloading. MSDN tutorial here.

Andrew
+6  A: 

You can overload operators in C#:

Before you decide to use operator overloading, please read at the very least, the following:


EDIT in response to op's edit:

The += is a non-overloadable operator. However, it resolves to +, and + is overloadable. Have a look here for which operators you can and can not overload.

Operators that can be overloaded:

+, -, !, ~, ++, --, true, false

+, -, *, /, %, &, |, ^, <<, >>

==, !=, <, >, <=, >= (The comparison operators can be overloaded but see note in link)

Kyle Rozendo
Thanks it helped me
+3  A: 

It does allow operator overloading..

that said, it's generally recommended not to override operators since it changes the semantics of your code and therefore makes it less maintainable by others.

Paul
Unless the overloaded operators provide appropriate semantics for the objects they're operating on. The classic example of '+' on a Complex number class is a perfectly acceptable use of operator overloading.
Andrew
Plus the casting operators for example in Linq to XML make reading element values very elegant.
Tim Jarvis
@Andrew, thanks for clarifying that.
Paul
A: 

You can overload operators in C#. Operator Overloading Tutorial

Benny Jobigan
+3  A: 

Operator overloading, C# allows. (Yoda version)

Şafak Gezer