Sorry, I was quite tired when I wrote this. That's why I confused some
things here. (At least I was the only one to find it out :-).)
By default, operator == works on reference types like
Object::ReferenceEquals, however types can override operator ==.
In C++/CLI and C#, operator == NEVER maps to Object::Equals.
Here is an app that shows how it works:
// eqt.cpp
// compile with "CL /clr:safe eqt.cpp"
using namespace System;
ref class ClassWithEquals
{
int i;
public:
ClassWithEquals(int i) : i(i) {}
virtual bool Equals(Object^ o) override
{
if (o == nullptr)
return false;
ClassWithEquals^ that = dynamic_cast<ClassWithEquals^>(o);
if (that == nullptr)
return false;
return this->i = that->i;
}
};
ref class ClassWithEqualityOperator
{
int i;
public:
ClassWithEqualityOperator(int i) : i(i) {}
bool operator==(ClassWithEqualityOperator^ that)
{
if (that == (Object^)nullptr)
return false;
return this->i == that->i;
}
};
int main()
{
ClassWithEquals^ cwe1 = gcnew ClassWithEquals(1);
ClassWithEquals^ cwe2 = gcnew ClassWithEquals(1);
if (cwe1 == cwe2)
Console::WriteLine("cwe1 == cwe2");
ClassWithEqualityOperator^ cwoe1 = gcnew ClassWithEqualityOperator(1);
ClassWithEqualityOperator^ cwoe2 = gcnew ClassWithEqualityOperator(1);
if (cwoe1 == cwoe2)
Console::WriteLine("cwoe1 == cwoe2");
}
If o
"Marcus Heege" <NO****@heege.net> wrote in message
news:u%****************@TK2MSFTNGP02.phx.gbl...
"Edward Diener" <ed*******************@tropicsoft.com> wrote in message
news:et**************@TK2MSFTNGP04.phx.gbl... Now that operator overloading allows to ref classes to be compared for
equality using == syntax, how does one compare the actual ref pointers
( ^ ) for equality instead ?
As an example:
SomeRefObject ^ obj1(..initialized somehow);
SomeRefObject ^ obj2(..initialized somehow);
if (obj1 == obj2) // This compares the objects themselves for equality in
C++/CLI I assume.
If SomeRefObject overwrites Equals, yes, otherwise no
How do I compare the ref pointers themselves ( ^ ) for equality ?
Object::ReferenceEquals(obj1, obj2)