11

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 1 and style 2 casting?
  • 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 :)

Community
  • 1
  • 1
Moon
  • 33,439
  • 20
  • 81
  • 132

1 Answers1

27

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 returns null 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. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
  • 1
    You didn't mention type conversion operators, which don't involve casting, but use the same syntax as casting. – Merlyn Morgan-Graham Jun 19 '11 at 06:27
  • 1
    @Merlyn: Ok I'll add that, thanks. :) @pst: Thanks for the cleanup! – user541686 Jun 19 '11 at 06:29
  • 1
    It is worth noting that `foo = bar as SomeType;` is faster than doing `if( bar is SomeType ) { foo = (SomeType)bar; }`, because the type is checked only once. And it is *much* faster than doing `try { foo = (SomeType)bar; } catch( InvalidCastException ) { }` if the conversion fails, because exceptions are quite expensive. – Sven Jun 19 '11 at 08:08