How to know if an object supports generic interface ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I'm trying to test whether an object (or type) implements a given generic
interface in C#.

Sample code :

public static bool DoesObjectImplementGenericIListInterface(Object o)
{
Type t = o.GetType();
return typeof(IList<>).IsAssignableFrom(t);
}

This code doesn't work. Any suggestions ?

Thanks
Yannick L.
 
Yannick said:
I'm trying to test whether an object (or type) implements a given generic
interface in C#.

Sample code :

public static bool DoesObjectImplementGenericIListInterface(Object o)
{
Type t = o.GetType();
return typeof(IList<>).IsAssignableFrom(t);
}

This code doesn't work. Any suggestions ?

I expect that only constructed types can be AssignableFrom another type.
So you might find that typeof(IList<string>).IsAssignableFrom(t), but I
believe it's necessary to resolve the type parameter before
IsAssignableFrom will ever return true.

In a way, this is the same discussion as the one about the base class: The
class List<T> is *not* a base class of List<string>.


Oliver Sturm
 
I totally understand that class List<T> is *not* a base class of List<string>.

I want to know at runtime if a type implements any form of IList<*>
interface. There must be a way to extract this information somehow using
Reflection ?

Yannick L.
 
Yannick said:
I totally understand that class List<T> is not a base class of
List<string>.

I want to know at runtime if a type implements any form of IList<*>
interface. There must be a way to extract this information somehow using
Reflection ?

Okay, I've found a way. You can do this:

Type objectType = typeof(myObject);
Type[] interfaceTypes = objectTypes.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
// if you check for interfaceType == typeof(IList<>) now
// you won't find it
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IList<>))
// now you have found an interface that was constructed
// from IList<T>

Hope this helps.


Oliver Sturm
 
Exactly what I needed ! Works like a charm.

Thanks !

Yannick L.

Oliver Sturm said:
Yannick said:
I totally understand that class List<T> is not a base class of
List<string>.

I want to know at runtime if a type implements any form of IList<*>
interface. There must be a way to extract this information somehow using
Reflection ?

Okay, I've found a way. You can do this:

Type objectType = typeof(myObject);
Type[] interfaceTypes = objectTypes.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
// if you check for interfaceType == typeof(IList<>) now
// you won't find it
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IList<>))
// now you have found an interface that was constructed
// from IList<T>

Hope this helps.


Oliver Sturm
 
Back
Top