DayTwo
DayTwo

Reputation: 759

should all c# classes implement Equals and GetHashCode?

should all c# classes override Equals and GetHashCode? For correctness

Upvotes: 3

Views: 451

Answers (5)

Ramiz Uddin
Ramiz Uddin

Reputation: 4259

When you override Equals, basically. When you want to provide a different idea of equality than simple reference equality.

String is a good example of this - two strings are equal (under a simple Equals call) if they represent the same sequence of characters. The hash code reflects this, such that if two strings are equal they will have the same hash code. (The reverse isn't necessarily true - two unequal strings can have the same hash code, but it's unlikely.)

(Strings are tricky in other ways, mind you - there are lots of different ideas of equality based on culture and casing, but String.Equals just looks at the UTF-16 code points which make up the string, and compares them in the simplest conceivable fashion.)

by Jon Skeet

Upvotes: 0

Oliver
Oliver

Reputation: 45119

Maybe not all, but all classes that will be put into a some kind of bag (IList, ICollection, IDictionary, Hashset, etc.) and need some simple method to differentiate them (just think about Sort(), Contains(), BinarySearch(), etc.).

If you use a class that way you should definitely implement them correct.

Upvotes: 0

Cody Gray
Cody Gray

Reputation: 244981

All classes already inherit these methods from the base class, System.Object.

You can choose to override the methods in derived classes if you need to be able to compare two instances of an object beyond simple reference equality, otherwise it's not necessary.

Remember, however, that if you choose to override one of them, you also need to override the other in order to ensure that Hashtables and dictionary keys, among other things, work properly with you derived class. The GetHashCode method needs to reflect the same logic as the Equals method. See here for more explanations and examples:

http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx

and

http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

Upvotes: 4

leppie
leppie

Reputation: 117330

No, they already do.

Whether you have to override them, is up to how it will be used. In most cases, it is not needed.

Upvotes: 11

Yves M.
Yves M.

Reputation: 3318

All classes to inherit this from the System.Object.

If you need to provide a specific Equals or GetHashCode for a class then you should override the methods in your classes. Otherwise just leave them..

http://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=VS.71).aspx

Upvotes: 3

Related Questions