Generics and Reflection

In .NET 2.0, reflection is extended to support generic type parameters. The type Type can represent generic types with specific type parameters (called bounded types), or unspecified (unbounded) types. As in C# 1.1, you can obtain the Type of any type by using the typeof operator or by calling the GetType() method that every type supports. Regardless of the way you choose, both yield the same Type. For example, in the following code sample, type1 is identical to type2:

    LinkedList<int,string> list = new LinkedList<int,string>();

    Type type1 = typeof(LinkedList<int,string>);
    Type type2 = list.GetType();
    Debug.Assert(type1 == type2);

Both typeof and GetType() can operate on naked generic type parameters:

    public class MyClass<T>
    {
       public void SomeMethod(T t)
       {
          Type type = typeof(T);
          Debug.Assert(type == t.GetType());
       }
    }

In addition, the typeof operator can operate on unbounded generic types (generic types that do not yet have specific type parameters). For example:

    public class MyClass<T>
    {}
    Type unboundedType = typeof(MyClass<>);

    Trace.WriteLine(unboundedType.ToString());
    //Writes: MyClass`1[T]

The number 1 being traced is the number of generic type parameters of the type used. Note the use of the empty <>. To operate on an unbounded generic type with multiple type parameters, use a , in the empty <>:

    public class LinkedList<K,T>
    {...}
    Type unboundedList = typeof(LinkedList<,>);
    Trace.WriteLine(unboundedList.ToString());
    //Writes: LinkedList`2[K,T]

To support generics, ...

Get Programming .NET Components, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.