Question:
In C#, when I need to check if a variable is of a certain type, I usually use the is
operator:
if(qualquerVariavel is int)
Console.Write("A variável é int");
I know it's also possible to check the type of a variable in other ways, one of which is using typeof
:
if(qualquerVariavel.GetType() == typeof(int))
Console.WriteLine("A variável é int");
What is the difference between these two operators? Are there others who "do the same thing" but with a little difference?
Answer:
-
is
checks the entire inheritance structure of the object; -
typeof()
returns the exact type of the object.
To better illustrate:
class Animal { }
class Cachorro : Animal { }
var a = new Cachorro();
Console.WriteLine(a.GetType() == typeof(Animal)) // false
Console.WriteLine(a is Animal) // true
Console.WriteLine(a.GetType() == typeof(Cachorro)) // true