Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.