What is the difference between typeof (T) vs. object.GetType ()

11

What's the difference?

Is there a difference between performance?

    
asked by anonymous 18.03.2014 / 14:57

2 answers

16

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"
}
    
18.03.2014 / 15:08
3

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:

  • You do not need to know the type at compile time (and usually you do not know).
  • You need to have an instance of the type (otherwise you will not you can call GetType ).
  • The actual type does not have to be accessible to your code - for example, could be an inner type in a different assembly.
  • A curious point: GetType will give unexpected answers about null value types.

      

    Source: this answer in StackOverflow

        
    18.03.2014 / 15:07