Monday, July 12, 2010

C# Prefix Casting vs 'as' Casting

The main difference between the two types of casting is what happens when an error occurs.

Prefix Casting: In prefix casting [ Type myVar = (Type)someVar; ] an error will be thrown and must be caught if someVar is not actually of type 'Type'.

'as' Casting: In as casting [ Type myVar = someVar as Type; ] the cast will return 'null' if someVar is not of type 'Type'.

I've read that 'as' Casting is also about five times faster (5x) than prefix casting. I've run my own tests and found out that it really isn't. Or at least not in loops. I've tried converting both 'string' and 'DateTime' objects to object. Prefix was much faster when adding to a list and sometimes faster when just converting the value to another variable.


No comments:

Post a Comment