Wednesday, May 14, 2008

[C#] Explicit Typecasting - ( ) vs "as"

One thing that confused me when starting out, was the seemingly intangible difference between typecasting via ([type])object and object as [Type]. With a small amount of digging here is what I found.

Two Methods of Explicit Typecasting

- Will raise an exception if the typecast is not valid.
- Seems to have slightly more overhead in execution time [(1)][(2)]
- Works well with classic value types [int, double] [(1)]
- Will return null if the typecast is not valid.
- Seems to have slightly less overhead in execution time.
- Only works for reference conversions and boxing conversions [(1)]
* Note: I believe the following is "boxing":
int myInt = 4;
Object myObj = myInt; // <-- now myInt is boxed into myObj.
int testInt = myObj as int // <-- can do this with as operator.
References:

No comments: