Possible Duplicate:
casting vs using the 'as' keyword in the CLR
I have seen two different ways of casting in C#.
For example:
MyObj foo = (MyObj) bar; // this is what I see most of the times
MyObj foo = bar as MyObj; // I do see this sometimes
style 1
and style 2
casting?Thanks a lot for looking into this :)
The first one (a "direct" or "C-style" cast) throws an exception if the cast is invalid. It is also the only way to perform actual type conversion on the object. (Note that type conversion is different from casting, because casting merely changes the type of the variable, whereas type conversion gives you a *different type of object.)
The second one (no particular name, although you can call it "try cast" as it's called in VB.NET) evaluates to null
instead of throwing an InvalidCastException
. (Because of this behavior it only works for reference types).
No major performance issues compared to each other.
You use as
only if you expect that your result might not be valid. Otherwise, use the first one.
By the way, MSDN might be helpful for parts of your question:
The
as
operator is like a cast operation. However, if the conversion is not possible, as returnsnull
instead of raising an exception. Consider the following expression:expression as type
It is equivalent to the following expression except that expression is evaluated only one time.
expression is type ? (type)expression : (type)null
Note that the
as
operator only performs reference conversions and boxing conversions. Theas
operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With