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.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 ...

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