Recipe4.3.Getting the Type of a Generic Type


Recipe 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>(); Type alsoGT = sgI.GetType(); 

Discussion

The type of the generic class cannot be retrieved directly because there is no type for a generic class without a type parameter provided. (See Recipe 4.2 for more information.) Only instantiated generic classes with a type parameter provided have a Type.

If you attempt to use the typeof operator with just the generic type definition and no type parameters, you will get the following error:

 // This produces an error: //Error 26 Using the generic type 'CSharpRecipes.Generics.SimpleGeneric<T>' // requires '1' type arguments Type gt = typeof(SimpleGeneric); 

See Also

See Recipe 4.2; see the "typeof" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net