5

My class structure (simplified)

interface Foo<T> { }
abstract class Bar1 : Foo<SomeClass> { }
abstract class Bar2 : Foo<SomeOtherClass> { }
class FinalClass1 : Bar1 { }
class FinalClass2 : Bar2 { }

Now, having only the type FinalClass1 and FinalClass2 I need to get their respective T types from the Foo interface - SomeClass for FinalClass1 and SomeOtherClass for FinalClass2. The abstract classes can implement more generic interfaces, but always only one Foo.

  1. How can I achieve this, using reflection?

  2. How can I also ensure that the type is implementing Foo regardless of what type the T is? Something like

bool bIsFoo = typeof(SomeType).IsAssignableFrom(Foo<>)

The above doesn't work.

DemoBytom
  • 305
  • 1
  • 9

1 Answers1

5

Search type interfaces for generic interface which is Foo<>. Then get first generic argument of that interface:

type.GetInterfaces()
    .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Foo<>))
    ?.GetGenericArguments().First();

If you want to check whether type is implementing Foo<>:

type.GetInterfaces()
    .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Foo<>))
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459