
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
226
|
Chapter 4: Generics
See Also
See the “Generic Type Parameters” and “Generic Classes” topics in the MSDN
documentation.
4.3 Getting the Type of a Generic Type
Problem
You need to get the Type object for a generic type instance at runtime.
Solution
Provide the type parameters when using the typeof operator; or instantiate the
generic type using the type parameters, then use the
GetType( ) method.
Given a regular type and a generic type like this:
public class Simple
{
public Simple( )
{
}
}
public class SimpleGeneric<T>
{
public SimpleGeneric( )
{
}
}
the type can be retrieved for the simple type at runtime using the typeof operator
with just the name of the simple type. For the generic type, the type parameter must
be provided in the call to
typeof. However, the simple type instance and the generic
type instance can both call
GetType( ) in the same manner.
Simple s = new Simple( );
Type t = typeof(Simple);
Type alsoT = s.GetType( );
// Provide a type parameter and you can get the
// instantiated type.
Type gtInt = typeof(SimpleGeneric<int>);
Type gtBool = typeof(SimpleGeneric<bool>);
Type gtString = typeof(SimpleGeneric<string>);
// You can also use the regular old GetType call from an instance
// as it has to be of an instance of the generic class.
SimpleGeneric<int> sgI = new SimpleGeneric<int>( ...