BlackWaspTM
Reflection
.NET 1.1+

The System.Type Class

The second part of the Reflection tutorial looks at the System.Type class. This class can be used to represent a type declaration, such as that of a class or structure, and obtain information about that type and its members.

System.Type

The starting point for most reflection operations is the Type class, found in the System namespace. Type instances provide information about types, such as classes, structures, enumerations, arrays, etc. This information can be extracted from the Type class' methods and properties, some of which give information directly and some of which obtain other Type instance or other objects that can be used to reflect over the original type's members and related types.

In this article we'll look at the basics of instantiating a Type object for standard .NET framework types and user-defined types. We'll also read some of the common Type properties. To begin, we need some types to reflect over. Create a console application project named, "ReflectionTest" and add the following code:

namespace ReflectionTest
{
    class Program
    {
        static void Main()
        {
        }
    }

    public class PublicClass
    {
        private struct PrivateNestedStruct { }

        public sealed class PublicNestedClass { }
    }

    public abstract class AbstractClass { }

    internal interface InternalInterface { }

    enum Enumeration { }
}

Obtaining Type Instances

There are several ways in which you can create an instance of the System.Type class. The choice that you make will be based upon the situation so the three main methods are described below.

Obtaining a Type Instance for a Known Type

When you wish to obtain information for a specific type, and that type is in the scope of your solution, you can create a Type object for it using the typeof keyword. The name of the type is provided to this keyword as the only parameter. You can either provide the fully qualified type name or a shorter version if you have included a suitable using directive in your code.

The code below obtains information about the PublicClass type and outputs its full name. You can try this out by adding it to the Main method.

Type t = typeof(PublicClass);
Console.WriteLine(t.FullName);  // ReflectionTest.PublicClass

Obtaining a Type from an Existing Object

If you do not have the name of a type but do have an object whose type you would like to examine, you can obtain a Type instance by executing its GetType method. This method is present in all .NET framework types and any classes and structures that you create yourself.

For example:

object o = new PublicClass();
Type t = o.GetType();
Console.WriteLine(t.FullName);  // ReflectionTest.PublicClass
5 February 2012