Question

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?

Was it helpful?

Solution

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/

OTHER TIPS

  • The as method returns null if cast fails.
  • The () method throws and error if the cast fails.

If the value of variable is not compatible with MyObject, myObject1 will contain null and you will be surprised by a null pointer error (1009 : cannot access a property or method of a null object reference.) somewhere later in the program when you try to access it. Where as if you are casting using the MyObject(variable) syntax, you will get a type coercion error (1034 : Type Coercion failed: cannot convert _ to _) at the same line itself - which is more helpful than getting a 1009 somewhere later and wondering what went wrong.

I think I read somewhere on this site that as is slighty faster than (), but I can't find the question again.

Beside that this question have been asked many times, you will find an more in-depth answer here.

I recently discovered the very useful [] tag when searching on StackOverflow, it allows to only search in questions tagged with the specified tag(s). So you could do a search like [actionscript-3] as vs cast. There are more search tips here: https://stackoverflow.com/search.

And no; the irony in that I can not find the question about performance and write about how to search is not lost on me ;)

I think as returns back the base class and not null when the casting fails and () throws an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top