C# FAQ: How to obtain type information on the fly using typeof

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How to obtain type information on the fly using typeof?

.NET assemblies contain detailed type information describing the structure of every internal and external type. This can be verified by loading an assembly into ildasm.exe and typing Ctrl-m. Many methods in the .NET base class libraries require passing in the type information for a given item. There are several approaches to obtaining type information for a given method invocation.

Firstly, all types inherit the public System.Object.GetType() method. So, the following example will work:

// Get type information from a variable.
 
TestType tt = new TestType();
Type tipe = tt.GetType();
RequiresTypeInfo (tipe);       // Imaginary method requiring type 

However, it may seem rather involved and expensive to create a type simply to call the inherited GetType() method. The C# language offers the typeof operator to simplify the process. The typeof operator does not require the creation of the item in question. Instead, just specify the name of the type as an argument as in the following:

// Get type information using the typeof operator.
 
RequiresTypeInfo (typeof (TestType)); // Imaginary method requiring type 


Personal tools