Question

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);
}
Was it helpful?

Solution

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.

OTHER TIPS

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

I know its an old question, but if you're going to overload the == or Object.Equals method, you should also overload the reverse operator !=.

And in this case, since you're comparing internal numbers, you should overload the other comparison operators <, >, <=, >=.

People who consume your class in the future, whether it be third-party consumers, or developers who take over your code, might use something like CodeRush or Refactor, that'll automatically "flip" the logic (also called reversing the conditional) and then flatten it, to break out of the 25 nested if's syndrome. If their code does that, and you've overloaded the == operator without overloading the != operator, it could change the intended meaning of your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top