views:

48

answers:

3

You can upcast or downcast an instance (to a superclass or subclass) using this syntax:

var i:MyClass = MyClass(instance);

But what does the as keyword do?

var i:MyClass = (instance as MyClass);

Are they equivalent? or am I missing something here...

+2  A: 

This article explains it nicely.

George Profenza
+2  A: 

To put it in a few words:

  • as is an operator. The reference states: "If the first operand is a member of the data type, the result is the first operand. Otherwise, the result is the value null"
  • the latter attempts a conversion. For primitives, this basically works, for complex values, this throws an exception unless the value is a member of the required type.

suppose, you have a class A and a class B.

var s:String = "4a";
trace(s as int);//null
trace(int(s));//4
var b:B = new B();
trace(b as A);//null
trace(A(b));//throws an error

greetz
back2dos

back2dos
A: 

You can read as well about performance issues involvedo in Casting Performance.

HTH,

J

Zárate