-2

Possible Duplicate:
Casting: (NewType) vs. Object as NewType
Casting vs using the 'as' keyword in the CLR

What is the difference between these 2 types of conversion(as i've seen, they don't work both all the time) :

ClassA a = (ClassA)someClassObject;

and

ClassA a = someClassObject as ClassA
Community
  • 1
  • 1
Alex
  • 10,869
  • 28
  • 93
  • 165

4 Answers4

2

Per http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx (emphasis mine):

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:

expression as type

is equivalent to:

expression is type ? (type)expression : (type)null

except that expression is evaluated only once.

ziesemer
  • 27,712
  • 8
  • 86
  • 94
1

In the first case an InvalidCastException will be thrown at runtime if the cast doesn't succeed. In the second case you will get null in the result variable.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

The first is casting - if someClassObject cannot be cast, an InvalidCastException will be thrown.

The second will not throw an exception, but a will be null if the cast does not succeed.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

As will return null and cast will exception from memory

undefined
  • 33,537
  • 22
  • 129
  • 198