O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required