Click here to Skip to main content
15,886,664 members
Articles / General Programming
Tip/Trick

Using Prefix vs As casts in C#

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
6 May 2010CPOL1 min read 9.6K   1  
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...
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.

License

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


Written By
Technical Lead Microsoft India R&D Pvt. Ltd. Hyderabad
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --