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.Equals

override Object.GetHashCode()?

I'm getting the following error when trying to override the Object.Equals()?

`TreehouseDefense.Point' overrides Object.Equals(object) but does not override Object.GetHashCode()

function still doesn't work when ran.

Snapshot: https://w.trhou.se/txmpccffb2

1 Answer

According to Microsoft Docs:

Derived classes that override GetHashCode() must also override Equals(Object) to guarantee that two objects considered equal have the same hash code; otherwise, the Hashtable type might not work correctly. https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.7.2

In a nutshell, GetHashCode is used in things like dictionaries (it doesn't use the object itself as the key, but rather a "hash code" which is much more lightweight and more efficient than a big clunky object). A hash code should uniquely identify an object to prevent "collisions" in which two objects that aren't equal can have the same hash code. If two objects are equal, their hash code should be the same and if two objects are not equal their hash code should not be the same. Therefore the Equals and GetHashCode methods are closely related.