What's the difference?
Is there a difference between performance?
What's the difference?
Is there a difference between performance?
typeof(T)
should be used in types , not in variables . Its goal is to get a Type
object from a known type at compile time. However, object.GetType
returns the actual type of an object (i.e. its "dynamic type"), regardless of which variable is referencing it (its "static type").
class Animal { }
class Cachorro : Animal { }
Animal x = new Cachorro(); // O tipo estático é "Animal", o dinâmico é "Cachorro"
if ( x.GetType() == typeof(Cachorro) ) {
// Executa um código só se o tipo do objeto for "Cachorro"
}
More information on SOEN question . It should be noted that there is still a third option for checking types, is
, which takes into account the class hierarchy:
Object x = new Cachorro(); // O tipo estático é "Object", o dinâmico é "Cachorro"
if ( x is Animal ) {
// Vai entrar nesse bloco, pois "Cachorro" é um subtipo de "Animal"
}
You can only use typeof()
when you know what type at compile time, and you are trying to get the type of the corresponding object. (Although the type could be a generic type parameter, for example, typeof(T)
within a class with a T
parameter.) Not necessarily being all instances of these types available to use typeof
. The operand for typeof
is always the name of a type or type of parameter. It can not be a variable or anything like that.
Now compare this to Object.GetType()
. This will get the actual object type. This means that:
GetType
). A curious point: GetType
will give unexpected answers about null value types.
Source: this answer in StackOverflow