Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get base interface of an interface by reflection in C# [duplicate]

Tags:

c#

reflection

How can I get base interface of an interface by reflection? I have tried to call BaseType propery, but value of It is null. After that I need to find generic type class of interface.

I need to find Foo type from the type of ISomeInterfaceForItem on this sample.

Type oType = typeof(ISomeInterfaceForItem);

Type oBase = oType.BaseType; // equals null

public interface ISomeInterfaceForItem: ISomeInterface<Foo>
{        
}

public interface ISomeInterface<T>
{
}
like image 521
hkutluay Avatar asked Jan 05 '23 22:01

hkutluay


2 Answers

Interfaces do not participate in inheritance, so BaseType makes no sense. Instead, you need to see what kinds of interfaces are implemented by the given type:

oType
  .FindInterfaces((t, _) => t.IsGenericType && t.GetGenericTypeDefinition() 
                            == typeof(ISomeInterface<>), null)
  .Select(i => i.GetGenericArguments().First())

Note that one class can implement multiple variants of ISomeInterface<> - e.g. class MyClass : ISomeInterface<Foo>, ISomeInterface<Bar> - that's why the result of the sample above is an enumerable of types, rather than just a single type.

like image 141
Luaan Avatar answered Jan 26 '23 11:01

Luaan


You can get the inherited interfaces using GetInterface() and enumerate the generic arguments using GetGenericArguments():

Type generic = typeof(I2).GetInterface("ISomeInterfaceForItem`1")?.
                          GetGenericArguments().FirstOrDefault();
like image 20
René Vogt Avatar answered Jan 26 '23 13:01

René Vogt