Ultimate casting showdown: is vs. as

I know that many C# developers scratch their heads all the time, wondering how casting in really works and where lies the difference between the is and as keywords in C#.

Let’s dive in

To make this article easy to understand I won’t go into much detail.

For illustration purposes, imagine we have two classes – Car and Student. Obviously, these two classes do not belong to the same inheritance tree. All they have in common is that they both derive from System.Object. This piece of will be common for all upcoming examples.

Explicit casting

Now that we have declared the two objects, we can perform a casting operation. We will assign the student object to the car object. Unfortunately, this will fail. Using explicit casting, we will be informed about such problem by an InvalidCastException, which means the remaining Console.WriteLine statement won’t be executed.

As

If casting is valid, the car object will be assigned the value of the student object. Otherwise, it will have the value of null.

When using the as keyword, checks against the null value have to be carried out. This is done within the if statement. If all goes well, we should see “All went good” printed to the console.

Is

As far as the is keyword is concerned, we have a pretty straightforward and type-safe approach to deal with casting.

Within an if statement we simply check if the cast would be valid. Following this check, we can proceed to explicit conversion, a.k.a. explicit cast.

This method, however, is quite inefficient, because at first we check the types and then carry out the cast. It’s true in situations when we know the cast will go through.

Leave a Reply

Your email address will not be published. Required fields are marked *