Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if type implements ICollection<T> [duplicate]

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

The below code doesn't work

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

What's a good way of detecting if a type implements a generic interface?

like image 615
np-hard Avatar asked Sep 24 '09 14:09

np-hard


2 Answers

CustomCollection c = new CustomCollection();

bool implementICollection = c.GetType().GetInterfaces()
                            .Any(x => x.IsGenericType &&
                            x.GetGenericTypeDefinition() == typeof(ICollection<>));
like image 172
Stan R. Avatar answered Sep 29 '22 11:09

Stan R.


An alternative to the others is the following:

if (MyObject is ICollection<T>)
  ...

Note: This will only work if T is known at compile time.

like image 40
Bomlin Avatar answered Sep 29 '22 11:09

Bomlin