What's difference between these casts?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I can do either:

string s = (string)someObject;

or

string s = someObject as string;

Then I can do:

int i = (int)someObject;

but I cannot do:

int i = someObject as int;

Why is there a difference? I thought the as keyword was just another way to
do a simple type cast? Or is there some benefit to using the as keyword which
leads to better performance over doing the traditional type cast, which value
types cannot take advantage of?
 
MrNobody said:
I can do either:

string s = (string)someObject;

or

string s = someObject as string;

Then I can do:

int i = (int)someObject;

but I cannot do:

int i = someObject as int;

Why is there a difference? I thought the as keyword was just another way
to
do a simple type cast? Or is there some benefit to using the as keyword
which
leads to better performance over doing the traditional type cast, which
value
types cannot take advantage of?

The difference between

T t = (T)o;
and
T t = o as T;

Is that the first one will throw in InvalidCastException if o is not, in
fact, of type T. The second will not throw an exception, and will leave t
set to null.

So then

int i = o as int;

must not compile since int is a ValueType and cannot be null.

David
 
MrNobody said:
I can do either:

string s = (string)someObject;

or

string s = someObject as string;

Then I can do:

int i = (int)someObject;

but I cannot do:

int i = someObject as int;

Why is there a difference? I thought the as keyword was just another way to
do a simple type cast?

Not quite. It returns null if the value isn't of the appropriate type,
rather than throwing an exception. As you can't assign null to a value
type variable, it doesn't make sense to use the "as" operator with
value types.
Or is there some benefit to using the as keyword which
leads to better performance over doing the traditional type cast, which value
types cannot take advantage of?

"as" can lead to better performance. For instance:

if (x is Foo)
{
DoSomethingWith((Foo)x);
}

requires the type check to be done twice.

Foo y = x as Foo;
if (y != null)
{
DoSomethingWith(y);
}

requires the type check once, and a simple nullity check.
 
Back
Top