10.3. typeof operator

The typeof operator is used to get a representative System.Type object of a type or object. There is only one System.Type object for each type. C#'s typeof is very similar to java.lang.Object's getClass() method. getClass() returns a java.lang.Class object that represents the runtime type of a Java object.

Study this example.

 1: using System; 2: namespace Mok.Book{ 3: class Test{ 4: public static void Main(){ 5: Type t1 = typeof(int); 6: Type t2 = typeof(decimal); 7: Type t3 = typeof(string); 8: Type t4 = typeof(object); 9: Type t5 = typeof(Test); 10: 11: Console.WriteLine(t1); 12: Console.WriteLine(t2); 13: Console.WriteLine(t3); 14: Console.WriteLine(t4); 15: Console.WriteLine(t5); 16: } 17: } 18: } // end namespace  ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.