The difference between typeof and is operator in C#
In this tutorial, you will learn the difference between typeof and is operator in C#.
C# classes have a mechanism called inheritance. This allows new derived classes to be created by inheriting from a base class. The derived class can be upcast to function as the base class or downcast to the type of the original class.
It is a convenient mechanism, but in complex code, you may wonder, "Can this object be safely retyped?
In such cases, the typeof and is operator are used.
Both are used to determine the type, but they work a little differently.
Understand the difference between the two and use them appropriately.
typeof
You can use typeof to determine what the class you instantiate is.
To be precise, typeof retrieves the type declaration (Type class) from the class name.
On the other hand, an object class has a GetType() method to obtain its own type declaration.
By comparing the two, it can be determined if the object is of the class specified by typeof.
Sample code:
using System; namespace CSharp_TypeOf_Example { public class Program { public static void Main(string[] args) { Animal animal = new BigDog(); Console.WriteLine("typeof(Animal) == animal.GetType(): {0}", typeof(Animal) == animal.GetType()); Console.WriteLine("typeof(Dog) == animal.GetType(): {0}", typeof(Dog) == animal.GetType()); Console.WriteLine("typeof(BigDog) == animal.GetType(): {0}", typeof(BigDog) == animal.GetType()); Console.WriteLine("typeof(GreatBigDog) == animal.GetType(): {0}", typeof(GreatBigDog) == animal.GetType()); } } public class Animal { } public class Dog : Animal { } public class BigDog : Dog { } public class GreatBigDog : BigDog { } }
Output:
typeof(Animal) == animal.GetType(): False
typeof(Dog) == animal.GetType(): False
typeof(BigDog) == animal.GetType(): True
typeof(GreatBigDog) == animal.GetType(): False
is operator
The is operator can be used to check if it can be cast.
Unlike typeof, it returns true if the base class name is used.
Sample code:
using System; namespace CSharp_Is_Operator_Example { public class Program { public static void Main(string[] args) { Animal animal = new BigDog(); Console.WriteLine("animal is Animal: {0}", animal is Animal); Console.WriteLine("animal is Dog: {0}", animal is Dog); Console.WriteLine("animal is BigDog: {0}", animal is BigDog); Console.WriteLine("animal is GreatBigDog: {0}", animal is GreatBigDog); } } public class Animal { } public class Dog : Animal { } public class BigDog : Dog { } public class GreatBigDog : BigDog { } }
Output:
animal is Animal: True
animal is Dog: True
animal is BigDog: True
animal is GreatBigDog: False