Detect if type implements ICollection <T>

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

The following code does not work

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

What is a good way to determine if a type implements a common interface?

+6
reflection c #
source share
2 answers
 CustomCollection c = new CustomCollection(); bool implementICollection = c.GetType().GetInterfaces() .Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>)); 
+24
source share

An alternative to the rest is the following:

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

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

+1
source share

All Articles