You might say, "lets get all interfaces implemented by that object, first by getting its type (using
GetType()), then by calling
GetInterface(string name), passing in the type name in its mangled form".
This will work, however, this yields to error prone, non-type-safe code, plus, making us required to know how to build the relevant mangled string.
We would like something better. We would like to be able to get the generic type itself. Fortunately this can be easily done the following way:
Type genericCollectionInterfaceType = typeof(ICollection<>);
This will return the generic collection interface type. Now, what can we do with it? We wanted to test if a certain object implements this interface. However, a list of, say, strings, will NOT implement that interface. It will implement the
ICollection<String>interface, which is not the same as
What can we do? We need to build, in runtime, a generic interface type that corresponds to the interface signature of our object:
Type testedObjectType = testedObject.GetType();
Type genericType = typeof(ICollection<>).MakeGenericType(testedObjectType.GetGenericArguments());
Then we can use that type to test for assignability:
MakeGenericTypecreates a new
Typeobject that represents the type we are looking for. We pass it a list of types, in this case taken from the object itself (using
GetGenericArguments). Then we can check for assignability between the two.