R – flex3 type casting

actionscript-3apache-flexflex3

Does anyone know the real difference between the two ways of type casting in Flex 3?

var myObject1:MyObject = variable as MyObject;
var myObject2:MyObject = MyObject(variable);

I prefer to use the second method because it will throw an Error when type cast fails, whereas the first method will just return null. But are there any other differences? Perhaps any advantages to using the first method?

Best Answer

The second type of casting has different behaviour for top level(http://livedocs.adobe.com/flex/2/langref/) types, e.g. Array(obj) does not cast in the straightforward way you describe; it creates a new Array if possible from obj, even if obj is an Array.

I'm sure the times this would cause unexpected behaviour would be rare but I always use "as" for this reason. It means if I do

int(str) 

I know it's a cast in the "attempt to convert" sense of the word not in the "I promise it is" sense.

ref: got some confirmation on this from http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/

Related Topic