I’ve 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 verify from C# whether two instances of MyClass are equal I get a 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 wrongly?
The
==operator you are overloading is not accessible in C# and the linebool equal1 = a == bcomparesaandbby reference.Binary operators are overriden by static methods in C# and you need to provide this operator instead:
When overriding
==you should also override!=. In C# this is actually enforced by the compiler.