Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether an object implements a generic interface for any generic type

I want to test an object to see if it implements IDictionary<TKey,TValue> but I don't care what TKey and TValue are.

I can test if is a concrete instance of the framework Dictionary<,> like this:

bool isDict = type.IsGenericType && 
    (typeof(Dictionary<,>).IsAssignableFrom(type.GetGenericTypeDefinition());

but I can't think of a way to test for something that implements IDictionary<,>. This technique doesn't work for the interface; IsAssignableFrom return false if I test against the generic base type IDictionary<,>, which seems odd since it works for the concrete type.

Normally you would use is to test if something implements an interface, but of course this only works if I want to test for a specific generic interface. Or I would just test for a common ancestral interface, but unlike other generic data structures such as IList<> and ICollection<>, there is no unique non-generic interface from which the generic IDictionary<TKey,TValue> inherits.

like image 529
Jamie Treworgy Avatar asked Jun 05 '12 15:06

Jamie Treworgy


1 Answers

How about something like

return type.GetInterfaces()
           .Where(t => t.IsGenericType)
           .Select(t => t.GetGenericTypeDefinition())
           .Any(t => t.Equals(typeof(IDictionary<,>)));

which I'm sure that you can easily generalize for any generic type definition.

like image 89
jason Avatar answered Sep 22 '22 20:09

jason