Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# different ways of casting -- (T)obj vs obj as T [duplicate]

Tags:

c#

.net

casting

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 :)

like image 230
Moon Avatar asked Jun 19 '11 06:06

Moon


1 Answers

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.

like image 145
user541686 Avatar answered Oct 27 '22 00:10

user541686