Sunday, 22 January 2012

CSharp, Miscellaneous Type casting with is and as operator in C#

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
Post a Comment