Obtain Type Information on the Fly using typeof

Obtain Type Information on the Fly using typeof

  • Comments 2

All .NET assemblies contain vivid type information which describes the structure of every internal and external type (this can be verified by loading an assembly into ildasm.exe and clicking the ctrl-m keystroke). On a related note, many methods in the .NET base class libraries require you to pass in type information for a given item. When you need to obtain type information for a given method invocation, you have numerous approaches. First, all types inherit the public System.Object.GetType() method:

// Obtain type information from a variable.
SomeType c = new SomeType();
Type t = c.GetType();
INeedYourTypeInfo(t);

While this works, it is overkill to create a type simply to call the inherited GetType() method. To streamline the process, the C# language offers the typeof operator. The benefit is you are not required to create the item in question, rather simply specify the name of the type as an argument:

// Obtain type information via typeof.
INeedYourTypeInfo(typeof(SomeType));


Tip from Andrew Troelsen
Posted by: Duncan Mackenzie, MSDN
This post applies to Visual C# .NET 2002/2003

Leave a Comment
  • Please add 6 and 4 and type the answer here:
  • Post
Page 1 of 1 (2 items)