Search code examples
c#inheritancetypestype-systems

GetGenericTypeDefinition returns different types


Given that I have the following types

interface IMyInterface<T> { }
class MyClass<T> : IMyInterface<T> { }

How come the following 5 lines doesn't produce the same outcome?

var type1 = typeof(IMyInterface<>);
var type2 = typeof(IMyInterface<object>).GetGenericTypeDefinition();
var type3 = typeof(MyClass<>).GetInterfaces().Single();
var type4 = typeof(MyClass<object>).GetInterfaces().Single().GetGenericTypeDefinition();
var type5 = typeof(MyClass<object>).GetGenericTypeDefinition().GetInterfaces().Single();

type1, type2 & type4 are the same

type3 & type5 are the same


Solution

  • In the case of 3 and five, it is a different type; it is the IMyInterface<SpecificT> where SpecificT is the generic type parameter (not the actual known value, but the parameter itself) from MyClass<T> - i.e. it is dependent.

    This is different to the completely free (independent) T in IMyInterface<T>, which is what 1, 2 and 4 provide.

    If you rename the Ts, it becomes more obvious:

    interface IMyInterface<TA> { }
    class MyClass<TB> : IMyInterface<TB> { }
    

    Now check the .GetGenericArguments().Single().Name against each. For 1, 2 and 4 it is TA. For 3 and 5 it is TB.