Search code examples
c#gethashcodegettype

Is there a guranteed uniqueness for GetType().GetHashCode()?


Let's say I have a few classes:

MyClass1() {}

MyChild1() : MyClass1 {}

MyChild2() : MyClass2 {}

MyGrandchild1() : MyChild2 {}

etc.

I know that GetHashCode() by itself, does not guarantee uniqueness between any two different Objects, but I'm interested does that apply for any two Types as well? i.e.:

(1) is there a chance that: typeof(MyClass1).GetHashCode() == typeof(MyGrandchild1).GetHashCode() will return true?

(2) if there's a chance for (1): is there a chance that typeof(MyClass1) == typeof(MyGrandchild1) will return true?

(3) worst case scenario: is there a chance that typeof(int) == typeof(long) will return true?

EDIT I forgot to ask about case (4) typeof(int).GetHashCode() == typeof(long).GetHashCode(), is there a chance for that to return true?


Solution

    1. GetHashCode returns an integer, so there is a limit of unique values it can return. There is no limit of defined types, so yes, there is a chance that typeof(MyClass1).GetHashCode() == typeof(MyGrandchild1).GetHashCode() will return true.

    2,3. Hash code is never used to check equality. The only relation between hash code and equality is that equal objects should have the same hash code.

    Edit

    One more answer, plus a some explanations.

    1. Types implement reference equality. The CLR makes sure the instances are unique

    A Type object that represents a type is unique; that is, two Type object references refer to the same object if and only if they represent the same type. This allows for comparison of Type objects using reference equality.

    It means that Type can use (and it does) the standard object implementation of GetHashCode. This implementation returns a pseudo-random number when it's first called on each instance.

    So asking if typeof(int).GetHashCode() can be equal to typeof(long).GetHashCode() is basically asking if two pseudo-random numbers can be equal. Yes they can.

    If you want more details about object.GetHashCode() implementation, read this blog post