16.1 Retrieving the type of an instance


To retrieve the Type of an object, use System.Object 's GetType() method. System.Type has a Name field which tells you the type's name. Examine the following example:

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

Output:

 c:\expt>test MyClass 

Line 11 can be replaced by

 11:     Console.WriteLine(t.Name); 

to produce the same output. The ToString() method of the Type class prints out its Name property automatically, so passing t or t.Name to Console.WriteLine() does not make a difference.



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