Type casting with is and as operator in C#

I have been seeing many developers are casting between two types using is operator. As we know, we do have as operator also for type casting.

For purpose of this article, we are going to use below two classes,


Very first let us try to understand, how is operator works?


So , if we are running below code , we will get output as true because ofccouse p is a Player.


Now let us modify code a bit and check whether p is compatible to Math class or not? Since p is instance of class Player and 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 is operator like below,


In above snippet, C# checks type compatibility twice and it costs the performance. So to simplify above code and improve performance C# gives us as operator to compare.


as operator find type compatibility, If an object is not compatible with given type then as operator returns null.


2 responses to “Type casting with is and as operator in C#”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com