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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.72.176