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 line bool equal1 = a == b
compares a
and b
by reference.
Binary operators are overriden 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 should also override !=
. In C# this is actually enforced by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With