When and where to use GetType() or typeof()?

Nikhil Agrawal picture Nikhil Agrawal · Jul 3, 2012 · Viewed 143.1k times · Source

Why this works

if (mycontrol.GetType() == typeof(TextBox))
{} 

and this do not?

Type tp = typeof(mycontrol);

But this works

Type tp = mycontrol.GetType();

I myself use is operator for checking type but my understanding fails when I use typeof() and GetType()

Where and when to use GetType() or typeof()?

Answer

Jon Skeet picture Jon Skeet · Jul 3, 2012

typeof is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.

GetType() is a method you call on individual objects, to get the execution-time type of the object.

Note that unless you only want exactly instances of TextBox (rather than instances of subclasses) you'd usually use:

if (myControl is TextBox)
{
    // Whatever
}

Or

TextBox tb = myControl as TextBox;
if (tb != null)
{
    // Use tb
}