Difference between type castings?

  • Thread starter Thread starter Benny Raymond
  • Start date Start date
B

Benny Raymond

I'm starting to see a lot of
"somevar as sometype"

Just cause i'm curious, what's the difference between that and

(sometype) somevar

?
 
Hi Benny,

x = somevar as sometype
is equivalent to:
if somevar is sometype
x = (sometype) somevar;
else
x = null;

Thus, "somevar as sometype" never raises an InvalidCastException. If
the cast is illegal, null is returned instead.

Thi - http://thith.blogspot.com
 
Hi,

I would also like to add, that the "as" casting is not supported on
value types. For value types, you must always use the (cast) casting.

-Lenard
 
Hi Tim,

I'm not taking issue with you here, just wanted to get more info.

You say that "as" is generally safer. I'm thinking its not as you now
don't know if the cast is invalid. Only safer if you don't need to know??

Thoughts?

Simon
 
Sure you do know if it is invalid. If returns a null reference if it is
not valid.

When you are getting out objects from a non-typed DataRow for example or
other typeless container, it is easier to use "as" than to put every
member access into a try block. Of course you can do that - I guess it
is also personal preference, which one you use.

-Lenard
 
Hi,

If you have a null value, you can cast that to anything you like. If
will not be an error. I don't think this would be a problem.

-Lenard
 
Back
Top