What isn't mentioned in the above answers is intent -- why are you performing the conversion, and (more importantly) what happens on the lines after the conversion?
For example, I've seen code similar to the following a number of times:
if ((foo as SomeType).SomeMethod()) { /* ... */ }
This could be compared to the cast-using version:
if (((SomeType) foo).SomeMethod()) { /* ... */ }
So, which of these is better?
The cast is.
Using as
will result in a NullReferenceException
if the conversion fails.
Using a cast will result in an InvalidCastException
if the conversion fails.
Now tell me, which is a more useful exception for debugging? A NullReferenceException
, which could be produced by nearly anything, or an InvalidCastException
, which lets you know what actually went wrong?
Thus, only use as
if the conversion is actually optional (meaning that there must be a null
check before using the variable). Otherwise, use a cast, thus making your intentions more explicit.