Tutorial :After overloading the operator==, how to compare if two variables points at the same object?



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);  }  


Solution:1

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.


Solution:2

Try a.ReferenceEquals(b);


Solution:3

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


Solution:4

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »