Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Intermediate C# System.Object Object.GetHashCode

I don't understand why we supplemented the Equals with GetHashCode. Wasn't Equals perfect for or purpose here?

Equals would always be accurate whereas GetHashCode is only mostly accurate.

1 Answer

Allan Clark
Allan Clark
10,810 Points

As I understand it, hashcode is used to uniquely identify objects. In the Point example this is pretty trivial as any 2 Points that have the same X and Y values ARE the same point, even if they are stored as completely separate objects in memory. However, if we were thinking about cars for example, we cannot assume two cars with the same values (make, model, color etc) refer to the same instance of a car. In these types of cases, the Equals method will call the GetHashCode method to check if the objects in fact are the same.

In the case where the objects are the same you wouldn't need to override GetHashCode would you?

Allan Clark
Allan Clark
10,810 Points

You can't tell if objects are the same when you are writing the method because you don't have the objects, GetHashCode is just to create a unique ID for the objects. It makes very little sense to override this method when the objects in question are value objects (meaning they have no identity outside the values of their properties).

It is very rare that overriding it would be necessary, value objects would be checked by their value and reference objects would generally just be checked by their IDs.