Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would == be overridden in a different way to .equals?

Tags:

c#

equality

I understand the difference between == and .equals. There are plenty of other questions on here that explain the difference in detail e.g. this one: What is the difference between .Equals and == this one: Bitwise equality amongst many others.

My question is: why have them both (I realise there must be a very good reason) - they both appear to do the same thing (unless overridden differently).

When would == be overloaded in a different way to how .equals is overridden?

like image 305
w0051977 Avatar asked Jan 05 '18 20:01

w0051977


People also ask

When should you override the default equals () method?

In order to identity differences between two objects we need to override equals method.

How is equals () different than ==?

In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. If a class does not override the equals method, then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method.

Can == be overridden?

Terminology note: == is never overridden. It's overloaded.

Why do we override equals?

Why we override equals() method? It needs to be overridden if we want to check the objects based on the property. For example, we want to check the equality of employee object by the id. Then, we need to override the equals() method.


1 Answers

== is bound statically, at compile-time, because operators are always static. You overload operators - you can't override them. Equals(object) is executed polymorphically, because it's overridden.

In terms of when you'd want them to be different...

Often reference types will override Equals but not overload == at all. It can be useful to easily tell the difference between "these two references refer to the same object" and "these two references refer to equal objects". (You can use ReferenceEquals if necessary, of course - and as Eric points out in comments, that's clearer.) You want to be really clear about when you do that, mind you.

double has this behavior for NaN values; ==(double, double) will always return false when either operand is NaN, even if they're the same NaN. Equals can't do that without invalidating its contract. (Admittedly GetHashCode is broken for different NaN values, but that's a different matter...)

I can't remember ever implementing them to give different results, personally.

like image 51
Jon Skeet Avatar answered Oct 10 '22 19:10

Jon Skeet