10

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
np-hard
  • 5,725
  • 6
  • 52
  • 76

2 Answers2

31
CustomCollection c = new CustomCollection();

bool implementICollection = c.GetType().GetInterfaces()
                            .Any(x => x.IsGenericType &&
                            x.GetGenericTypeDefinition() == typeof(ICollection<>));
Stan R.
  • 15,757
  • 4
  • 50
  • 58
1

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.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Bomlin
  • 676
  • 4
  • 15