Sunday, September 02, 2007

Reflection on Generic, Part 1

You can use reflection against generic type to get metadata information about a generic type as well as instantiate a generic type with type argument. In this post, I will walk you through how to retrieve metadata about a generic type.

To check whether a type is a generic type, you use the Type.IsGenericType property.
Let start with a simple example:
Type s = typeof(string);
// This will print False.
Console.WriteLine(s.IsGenericType);
// This will print System.String
Console.WriteLine(s.FullName);

Since System.String is not a generic type, it will print False. Now let's use an example with generic type:
Type t = typeof(List<>);
// This will print True.
Console.WriteLine(t.IsGenericType);
// This will print System.Collections.Generic.List`1.
Console.WriteLine(t.FullName);
 
Type d = typeof(Dictionary<,>);
// This will print True.
Console.WriteLine(d.IsGenericType);
// This will print System.Collections.Generic.Dictionary`2.
Console.WriteLine(d.FullName);

In the above example, both will print True. Note that to retrieve type metadata for a generic type, you need to use the <> after the generic type name to denote the number of type parameters specified for that generic type. The number of type parameters are part of the type signature. It is perfectly legal to declare the following:

class C1<Y> { ... }
class C1<Y,T> { ... }

Going back to the example, since List only has one type paratemer, I just specify <> to indicate I want to the List generic class with one type parameter. For Dictionary class take take two type parameter, I specify <,> to indicate I want the Dictionary generic class with two type parameter.

When print out the full name of the class, notice that there is a number at the end of the class name. The number is called Arity which indicate the number of type parameter that the generic type have.

Labels: , ,

0 Comments:

Post a Comment

<< Home