16 March 2008

Reflection: Type unraveled

The Type class in .NET is not the easiest to understand, I believe because of the many different "kinds of types" that are modeled by it: generic types, generic type parameters, reference types, pointer types, array types, etc. Furthermore, sometimes you have one kind of type (e.g. a generic type) and want to make another kind (i.e. "instantiate" a generic parameter with another type). The Type class offers all the necessary methods to do the feasible conversions; however it is not always easy to find. The following graph should help.

The boxes show the different kinds of types that exist. An example of Type1<> is typeof(IList<>); Type1<Type2> is typeof(IList<string>) and so on. The arrows denote how you can obtain one kind of type from the other. For example, if you have a generic type definition (e.g. typeof(IList<>)) you can make this into an instantiatable type (typeof(IList<string>))by calling typeof(IList<>).MakeGenericType(typeof(string)). With "#Type2" I mean a subtype of Type2.

Hope this helps someone.

PS the graph was laid out by Graphviz's dot layout. It was rendered using a self-made WPF control. More on that later.

Technorati : , ,
Del.icio.us : , ,

1 comment:

  1. It really helped me :-)
    Was really stuck in this Reflection problem where I need to reflect on the same object which may have IList(T) and I had to find T and then Invoke methods on T.