I have been seeing many developers casting between two types using the "is" operator. As we know, we also have the "as" operator for type casting.
For the purpose of this article, we are going to use the following two classes:
Let us first try to understand how the "is" operator works.
So if we are running the following code, we will get output as true because of course p is a Player.
Now let us modify the code a bit and check whether p is compatible to Math class or not? Since p is an instance of class Player and the Player class does not have Math class in hierarchy tree, so output we will get false.
If we compare an object against null, we will get always an output as false.
Normally we use the "is" operator like below:
In the above snippet, C# checks type compatibility twice and it costs the performance. So to simplify the above code and improve performance C# gives us the "as" operator to compare.
The "as" operator determines type compatibility; if an object is not compatible with the specified type then the "as" operator returns null.