Obtain Type Information on the Fly using typeof

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

Comments

  • Anonymous
    November 01, 2004
    I'm new to c# and .net. I'm trying to compile a class with a method that uses 'typeof' to check the type of an object variable passed into it. The problem is every time I try to compile (in VS.NET) the compiler complains that it can't find the namespace for the variable name (which obviously doesn't exist.) Any ideas how to get around this?
  • Anonymous
    March 12, 2008
    PingBack from http://bordercrossingstatsblog.info/c-frequently-asked-questions-obtain-type-information-on-the-fly/