Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type from base interface [duplicate]

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.

like image 359
DemoBytom Avatar asked Feb 06 '17 13:02

DemoBytom


People also ask

Can a generic type be an interface?

Java Generic Classes and Subtyping We can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.

Is it possible to inherit from generic type?

You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. . Net generics are way different from C++ templates.

How do you declare a generic interface?

Declaring Variant Generic Interfaces You can declare variant generic interfaces by using the in and out keywords for generic type parameters. ref , in , and out parameters in C# cannot be variant. Value types also do not support variance. You can declare a generic type parameter covariant by using the out keyword.

What does the generic constraint of type interface do?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.


1 Answers

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<>))
like image 52
Sergey Berezovskiy Avatar answered Sep 25 '22 16:09

Sergey Berezovskiy