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()
?
typeof
is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string).GetType
is called on an object at runtime. In both cases the result is an object of the typeSystem.Type
containing meta-information on a type.Example where compile-time and run-time types are equal
Example where compile-time and run-time types are different
i.e., the compile time type (static type) of the variable
obj
is not the same as the runtime type of the object referenced byobj
.Testing types
If, however, you only want to know whether
mycontrol
is aTextBox
then you can simply testNote that this is not completely equivalent to
because
mycontrol
could have a type that is derived fromTextBox
. In that case the first comparison yieldstrue
and the secondfalse
! The first and easier variant is OK in most cases, since a control derived fromTextBox
inherits everything thatTextBox
has, probably adds more to it and is therefore assignment compatible toTextBox
.Casting
If you have the following test followed by a cast and T is nullable ...
... you can change it to ...
Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the
as
operator followed by a test fornull
is more performing.Starting with C# 7.0 you can simplify the code by using pattern matching:
Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:
This is because either the value is
null
or it is anint
. This works forint? o
as well as forobject o = new Nullable<int>(x);
:I like it, because it eliminates the need to access the
Nullable<T>.Value
property.typeOf is a C# keyword that is used when you have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.
You may find it easier to use the
is
keyword:typeof
is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand oftypeof
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:Or