16.2 Retrieving the type from a name of a class


16.2 Retrieving the type from a name of a class

If you want to retrieve the Type of a class represented by a string instead, you can use the static GetType() method of the Type class. Examine the following code.

 1: using System;  2: using System.Reflection;  3:  4: public class MyClass {  5: }  6:  7: public class MainClass {  8:   public static void Main () {  9:  Type t  =  Type.GetType("MyClass");  10:     Console.WriteLine(t); 11:   } 12: } 

You can try this to retrieve the Type representation of an int :

 Type t = Type.GetType("System.Int32"); 

It is illegal to do the following though:

 Type t = Type.GetType("int"); 

because int is just a C# alias for System.Int32 . Type.GetType only takes in strings representing types of the CTS.

Alternatively, you can use C#'s typeof operator instead of Type.GetType() to do the same trick:

 1: public class TestClass { 2:   public static void Main () { 3:  Type t  =  typeof("MyClass");  4:     Console.WriteLine(t); 5:   } 6: } 

The main difference between using typeof and Type.GetType() is that the former is evaluated at compile time (and hence is faster during execution) while the latter is evaluated during runtime (See section 10.3.1).

System.Type has several methods which are useful for telling us more about the type. The method names are self-explanatory: FullName , IsAbstract , IsClass , IsInterface , IsPublic , IsSerializable , IsSealed , etc. Consult the BCL API documentation for the other members of Type .



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

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