views:

310

answers:

3

Overloading the comparison operator, how to compare if the two variables points to the same object(i.e. not value)

public static bool operator ==(Landscape a, Landscape b)
{
    return a.Width == b.Width && a.Height == b.Height;
}

public static bool operator !=(Landscape a, Landscape b)
{
    return !(a.Width == b.Width && a.Height == b.Height);
}
+5  A: 

Try a.ReferenceEquals(b);

mquander
+8  A: 

Use the Object.ReferenceEquals static method.

Of course, in order for the == and != method to retain their full functionality, you should also be overriding Equals and GetHashCode so that they return a consistent set of responses to callers.

Steve Mitcham
+4  A: 

To check whether both points to same object. You should use Object.ReferenceEquals method. It will return true if both are same or if both are null. Else it will return false

Towardsnext