C Sharp

The Type Class

At the center of reflection is the System.Type class. The System.Type class is an abstract class that represents a type in the Common Type System (CTS) and enables you to query for type name, the type's encompassing module and namespace, and whether the type is a value type or a reference type.

Retrieving the Type of an Instance

The following example shows how to retrieve a Type object for an instantiated int: -

using System;
using System.Reflection;
class TypeObjectFromInstanceApp
{
    public static void Main(string[] args)
    {
        int i = 6;
        Type t = i.GetType();
        Console.WriteLine(t.Name);
    }
}

Retrieving the Type from a Name

Besides retrieving a variable's Type object, you can also create a Type object from a type name. In other words, you don't need to have an instance of the type. Here's an example of doing this for the System.Int32 type: -

using System;
using System.Reflection;
class TypeObjectFromNameApp
{
    public static void Main(string[] args)
    {
        Type t = Type.GetType("System.Int32");
        Console.WriteLine(t.Name);
    }
}

Note that you cannot use the C# aliases when calling the Type.GetType method, because this method is used by all languages. Therefore, you cannot use the C# specific int in place of System.Int32.