Obtain Type Information on the Fly using typeof

Published 20 October 04 10:54 AM

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

Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# GeoffN said on November 2, 2004 5:54 AM:
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?
# Border Crossing Stats » C# Frequently Asked Questions : Obtain Type Information on the Fly … said on March 13, 2008 12:18 AM:

PingBack from http://bordercrossingstatsblog.info/c-frequently-asked-questions-obtain-type-information-on-the-fly/

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker