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,

clip_image002

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

clip_image004

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

clip_image006

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.

clip_image008

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

Normally we use is operator like below,

clip_image010

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.

clip_image012

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

clip_image013

About these ads

2 thoughts on “Type casting with is and as operator in C#

  1. Pingback: Monthly Report March 2011: Total Posts 15 « debug mode……

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s