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 trialokilydokily
12,105 PointsI 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
10,810 PointsAs 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.
okilydokily
12,105 Pointsokilydokily
12,105 PointsIn the case where the objects are the same you wouldn't need to override GetHashCode would you?
Allan Clark
10,810 PointsAllan Clark
10,810 PointsYou 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.