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

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:


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


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


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. 


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

Normally we use the "is" operator like below: 


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.


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


 Subscribe to Articles


Further Readings:


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