Google Search

Wednesday, April 15, 2009

Runtime testing and casting objects of generic types

How can you tell, in runtime, if an object you have is of a specific generic type? For instance, if it implements the generic interface ICollection ?

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 ICollection<>.

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:
collectionType.IsAssignableFrom(testedObjectType);

Calling MakeGenericType creates a new Type object 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.

kick it on DotNetKicks.com

2 comments:

  1. The code in a form of a function:
    http://starterco.de/snippets/21/g/23

    ReplyDelete
  2. How to register and play at Slots.lv - Tricktactoe
    How 벳존 to register 안전놀이터 and play 프리메라리가 순위 at Slots.lv. 월드컵주소 Register online for real money in casinos, and start playing 꽁머니 5000 today!

    ReplyDelete