Pattern Matching and casting using ‘is’ and ‘as’

In previous posts we discussed about casting using the ‘as’ operator instead of using the ‘classic way’ of casting (more info here). But there are a few things we need be careful when using ‘as’ and ‘is’ operators.


First of all let’s explain what the ‘is’ operator does.

In the following code

The is operator will return true if obj is an instance the type MyObject or an instace that derives from MyObject.

Some people use the ‘is’ operator in the following way

Now let’s see what is happening here. In the above code, we are basically checking if obj is of the type we want. If it is, cast it to that type, or else create a new instance of that type, so we can have something to work with.

But why is this wrong?

The above example is not good because of what is happening inside the operator is. What the is operator is doing, is in fact what we discussed in the previous article about the as operator. The is internally performs casting on the oject using the as operator and then performs a null check. If the result is not null (casting successful) it then returns true, or else returns false.
So the above example we mentioned, is in fact performing a cast twice. And as we know, casting is a costly procedure. we should avoid if not necessary.

So the above code should again be simplified to the example we mentioned before where we only use the as operator (and maybe the null coalescing operator (??) to simplify our code).

All in one neat line of code.

So where should we use the is operator?
The is should be used in cases where all you need to know is the variable you have in your hands, is an instance of a specific type, without needing the converted value.

Now let’s move on to the new feature introduced in C# 7 called pattern matching and discuss a small use case of it here.

In C# 7 we can the is operator differently in pattern matching. In cases where we wish to perform specific stuff if the object we have available is an instance of a class we want.
For example:

So what is the difference?

Well by using pattern matching, we can do everything in one line (boolean check and casting) and automatically use it inside the if statement.

Now we need to be carefull though. The variable x is still in scope after the if statement, but we cannot be sure it was assigned. We can only be sure it was assigned inside the if statement, and should assume, in all other cases that after it, it contains null value only.

So C# 7 again is making things clearer and more readable. As long as we are aware how to use them.

Leave a Reply