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
np-hard
source share2 answers
CustomCollection c = new CustomCollection(); bool implementICollection = c.GetType().GetInterfaces() .Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>)); +24
Stan R.
source shareAn alternative to the rest is the following:
if (MyObject is ICollection<T>) ... Note. This will only work if T known at compile time.
+1
Bomlin
source share