What is the difference between typeof(T) vs. Object.Gettype()

Asked

Viewed 677 times

11

What’s the difference?

Is there any difference between performance?

2 answers

17


typeof(T) should be used in guys, not in variables. Your goal is to obtain an object Type from a known compile-time type. Already the object.GetType returns the real 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 in that question in the SOEN. It is good to note that there is still a third option for checking types, the is, which takes into account the hierarchy of classes:

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"
}
  • Well validate your answer, understood yes, thank you

  • 2

    It is important to note that the verification x.GetType() == typeof(Animal) exception x is null, which does not happen in the verification x is Animal, in which if x is null, the return is false.

3

You can only use typeof() when you know what type at compile time, and you are trying to get the corresponding object type. (Although the type could be a generic type parameter, for example, typeof(T) within a class with a type parameter T.) It is not necessarily necessary for all instances of such types to be available to use the typeof. The operand to typeof is always the name of a type or parameter type. It cannot be a variable or anything like that.

Now compare that to Object.GetType(). This will get the real type of the object. It means that:

  1. You don’t need to know the type at compile time (and usually you don’t know).
  2. You need there to be an instance of the type (otherwise you don’t can call GetType).
  3. The actual type does not need to be accessible to your code - for example, could be an internal type in a different Assembly.

A curious point: GetType will give unexpected responses about null value types.

Source: that answer in Stackoverflow (in English)

  • thanks for the reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.