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
- So, what is the basic difference?
- What are the proper names for the
style 1andstyle 2casting? - How do I decide when to use what?
- Is there any major performance issues?
- Is there anything else I should know of related to this topic?
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
nullinstead of throwing anInvalidCastException. (Because of this behavior it only works for reference types).No major performance issues compared to each other.
You use
asonly 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: