Ishraq Ahmad
Blog for .net Architects & Developers looking to learn WPF, Silverlight, WCF and ASP.net MVC.
C# is versus as operators
In programming, most common scenario is to check if object is of given type, object is not null and then type cast it to given type. C# provides “is” and “as” operators to ease programming and an efficient way to implement this common scenario. Many developers get confuse about when to use “is” operator and when to utilize “as” operator powers. Let’s examine both operators and see which is better in terms of performance.
is Operator
- Checks if object is of given type.
- Never throws an exception even if object is null.
- Returns True or False.
-
When used in “if” condition, then CLR has to perform two cycles to check if object can be typed cast.
Example code:
// Here, car is object and Car is given type. Car car = new Car(); if( car is Car ) { // car is of type Car. }
as Operator
- Type casts object to given type.
- Never throws an exception even if object is null.
- Returns converted object if object can be typed cast to given type else null.
-
CLR has to perform only one cycle if object can be typed cast to given type.
Example code:
// Here, o is object and Car is given type. Car car = o as Car; if( car != null ) { // car is of type Car. }
Conclusion
Use “as” operator when possible because it improves performance and doesn’t throw exception.
Related posts: