views:

207

answers:

2

Hello,

I am trying to check if a type implements the generic Icollection interface, since this is a base interface for any of my generic collections.

the below code doesnt work

GetType(ICollection(Of)).IsAssignableFrom(
    objValue.GetType().GetGenericTypeDefinition())

whats a good way of detecting if a type implements a generic interface

many thanks

+8  A: 
CustomCollection c = new CustomCollection();

bool implementICollection = c.GetType().GetInterfaces()
                            .Any(x => x.IsGenericType &&
                            x.GetGenericTypeDefinition() == typeof(ICollection<>));
Stan R.
This is the correct answer; I've tested it
Ngu Soon Hui
+1  A: 

An alternative to the others is the following:

if (MyObject is ICollection<T>)

...

Note: This will only work if you have some way of knowing the type "T". Otherwise, this will not work for you.

Bomlin