Overloaded C ++ / CLI statement is not available through C #

I have the following C ++ / CLI class:

public ref class MyClass { public: int val; bool operator==(MyClass^ other) { return this->val == other->val; } bool Equals(MyClass^ other) { return this == other; } }; 

When I try to check with C # whether the two instances of MyClass are equal, I get the wrong result:

 MyClass a = new MyClass(); MyClass b = new MyClass(); //equal1 is false since the operator is not called bool equal1 = a == b; //equal2 is true since the comparison operator is called from within C++\CLI bool equal2 = a.Equals(b); 

What am I doing wrong?

+4
source share
1 answer

The == operator that you overload is not available in C #, and the line bool equal1 = a == b compares a and b by reference.

Binary operators are overridden by static methods in C #, and you need to provide this operator instead:

 static bool operator==(MyClass^ a, MyClass^ b) { return a->val == b->val; } 

When overriding == you must also override != . In C #, this is actually done by the compiler.

+10
source

All Articles