Hao
Hao

Reputation: 8115

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

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

Upvotes: 6

Views: 588

Answers (4)

Brian Deragon
Brian Deragon

Reputation: 2957

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.

Upvotes: 1

Steve Mitcham
Steve Mitcham

Reputation: 5313

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.

Upvotes: 9

user74561
user74561

Reputation:

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

Upvotes: 5

mqp
mqp

Reputation: 71937

Try a.ReferenceEquals(b);

Upvotes: 5

Related Questions