Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I trace object identity using GetHashCode?

What is the use of GetHashCode()? Can I trace object identity using GetHashCode()? If so, could you provide an example?

like image 348
user160677 Avatar asked Nov 27 '22 12:11

user160677


1 Answers

Hash codes aren't about identity, they're about equality. In fact, you could say they're about non-equality:

  • If two objects have the same hash code, they may be equal
  • If two objects have different hash codes, they're not equal

Hash codes are not unique, nor do they guarantee equality (two objects may have the same hash but still be unequal).

As for their uses: they're almost always used to quickly select possibly equal objects to then test for actual equality, usually in a key/value map (e.g. Dictionary<TKey, TValue>) or a set (e.g. HashSet<T>).

like image 135
Jon Skeet Avatar answered Dec 06 '22 16:12

Jon Skeet