I have the following general classes:
class Base<T> where T : ... { ... } class Derived<T> : Base<T> where T : ... { ... } class Another<T> where T : ... { ... } class DerivedFromDerived<T> : Derived<T> where T : ... { ... }
Somewhere in my code, I would like to check if a given pedigree element inherits from Base<T> without creating a specific generic instance. How to do it?
static bool DerivedFromBase(Type type) { } static void Main(string[] args) { Console.WriteLine(DerivedFromBase(typeof(Derived<>)));
EDIT: Thanks, Mark. Now I see the light. I initially tried the following:
typeof(Derived<>).BaseType == typeof(Base<>)
This seems to be correct. But this is not so. The problem is that Base T is not the same as Derived T. So in
typeof(Base<>)
Base T is a free type. But in
typeof(Derived<>).BaseType
Base T bound to Derived T , which in turn is a free type. (This is so amazing that I could LOVE see the source code for System.Reflection !). Now
typeof(Derived<>).BaseType.GetGenericTypeDefinition()
unbounds Base T Conclusion:
typeof(Derived<>).BaseType.GetGenericTypeDefinition() == typeof(Base<>)
And now, if you all excuse me, my head is on fire.
source share