Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI overloaded operator is not accessed via C#

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?

like image 670
Mauro Ganswer Avatar asked Dec 20 '22 16:12

Mauro Ganswer


1 Answers

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.

like image 150
Martin Liversage Avatar answered Dec 30 '22 11:12

Martin Liversage