.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
satyapriyanayak

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Type casting with is and as operator in C#

Posted By:Dhananjay Kumar       Posted Date: April 02, 2011    Points: 200    Category: C#    URL: http://www.dhananjaykumar.net  

In this articles we will see the difference bwtween "is" and "as" operator for type casting in C#
 

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

For the purpose of this article, we are going to use the following two classes:

Operator1.gif



Let us first try to understand how the "is" operator works.


Operator2.gif



So if we are running the following code, we will get output as true because of course p is a Player. 


Operator3.gif



Now let us modify the code a bit and check whether p is compatible to Math class or not? Since p is an instance of class Player and the Player class does not have Math class in hierarchy tree, so output we will get false. 


Operator4.gif

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

Normally we use the "is" operator like below: 

Operator5.gif



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



Operator6.gif



The "as" operator determines type compatibility; if an object is not compatible with the specified type then the "as" operator returns null. 


Operator7.gif

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend