Type casting with is and as operator in C#



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:

Operator1.gif

Let us first try to understand how the "is" operator works.

Operator2.gif

So if we are running the following code, we will get output as true because of course p is a Player.

Operator3.gif

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.

Operator4.gif

If we compare an object against null, we will get always an output as false.

Normally we use the "is" operator like below:

Operator5.gif

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.

Operator6.gif

The "as" operator determines type compatibility; if an object is not compatible with the specified type then the "as" operator returns null.

Operator7.gif

Up Next
    Ebook Download
    View all
    Learn
    View all