Click here to Skip to main content
Click here to Skip to main content

Using Prefix vs As casts in C#

By , 6 May 2010
Rate this:
Please Sign up or sign in to vote.
Yesterday during code review, one suggestion that came up from the reviewer was to always use Prefix-casting instead of As-casting in our code and that brings out the question why? The answer lies in choosing a tradeoff between reliability and performance. The primary difference between Prefix-casting and As-casting is the way these mechanisms handle exceptions / errors when the cast fails somehow. Consider this code,
PurchaseOrder po = ...; 
GeneralPurchaseOrder gpo = (GeneralPurchaseOrder) po; 
If the cast is invalid, then this will throw an exception.
Now, consider this code,
PurchaseOrder po = ...;
GeneralPurchaseOrder gpo = po as PurchaseOrder; 
If the cast is invalid, this will return null and it will let the program continue the execution. Yes, as-casting will definitely throw an exception but only when the specific type gpo in this case is referenced and it can be at any point of time in any piece of code in either files so harder to debug too.
On the other hand, CLR emits different codes (CastClass) when we use Prefix versus (IsInst) As casts and the instruction generated by CLR for As casting is significantly faster than the one generated for Prefix.
Conclusion is, use Prefix casting as a rule of thumb as reliability almost always gets an upper hand over performance, but if in your code, you have ample checks for nulls and you are absolutely confident on your type cast validations, then you may opt for using As-casting because research has shown that the performance margin is 5 times over Prefix casting.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sarang Date
Technical Lead Microsoft India R&D Pvt. Ltd. Hyderabad
India India
No Biography provided

Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 6 May 2010
Article Copyright 2010 by Sarang Date
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid