Monday, September 1, 2008

[.NET] Difference between GetType and typeof

GetType and typeof come in useful when you need to mess with objects types before casting and so forth.

The difference between the two is the following:
GetType is a method of the object class - from which everything inherits in .NET - while typeof is an expression that operates on a type (same as you declare variables with).
While GetType takes into account inheritance and gives you back the actual Type of your instance at runtime - typeof just resolves the type into a System.Type object (jeez) at compiletime.

To cut a long story short: GetType extracts the Type from the object - typeof extracts the correspondent System.Type object from a type (declaration).


Have a look @ an example and it will be clearer:
////////////////////////////////////////////////
Type myType;
//the following blocks of code are equivalent
{
myType = typeof(int);
}

{
int i;
myType = i.GetType();
}
/////////////////////////////////////////////////

Good stuff - ain't it? No, it ain't - this post is child of absolute boredom.

kick it on DotNetKicks.com

3 comments:

Raj said...

Good

Visual Studio Books said...

Thanks for the clarification of GetType vs TypeOf. I will use TypeOf since it is more concise and employs intellisense.

Anonymous said...

You are hilarious!! Nice post.