You can obtain information about the type of an object by using a mechanism called reflection.

The reflection mechanism in C# is handled by the System.Reflection namespace in the .NET Framework. This namespace contains classes and interfaces that provide a view of types, methods, and fields.

The System.Type class provides methods for obtaining information about a type declaration, such as the constructors, methods, fields, properties, and events of a class. A Type object that represents a type is unique; that is, two Type object references refer to the same object only if they represent the same type. This allows comparison of Type objects through reference comparisons (the == and != operators).

The typeof Operator

At compile time, you can use the typeof operator to return the type information from a given type name.

The following example retrieves run-time type information for the type byte, and displays the type name to the console.

using System;
using System.Reflection;
Type t = typeof(byte);
Console.WriteLine("Type: {0}", t);

The following example displays more detailed information about a class. Specifically, it lists the methods for that class.

using System;
using System.Reflection;
Type t = typeof(string); // Get type information
MethodInfo[ ] mi = t.GetMethods( );
foreach (MethodInfo m in mi) {
Console.WriteLine("Method: {0}", m);

GetType Method

The typeof operator only works on classes that exist at compile time. If you need type information at run time, you can use the GetType method of the Object class.