Friday, July 27, 2007

Casting Vs The “as” operator

source :
http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/

== quote ==
Just write a Flex app and try the following in a function

var btn:Button = new Button();

var lst:List = new List();

lst = List (btn);

In short, we are trying to cast a button into a list… What do you expect?? Yes… an RTE (Run Time Error)

It reads

TypeError: Error #1034: Type Coercion failed: cannot convert mx.controls::Button@16ab0479 to mx.controls.List.

There are times in your app development cycle, when you are not sure, if a particular casting is allowed or not. You definitely don’t want to throw an RTE (Run Time Error) to the user either. What you end up doing invariably is using a try…catch block to handle the RTE. A better and cleaner alternative to this is using the as operator

Using the as operator has the following advantages

* It does the exact same thing as casting does, if you are casting between compatible types
* It returns a null if the object cannot be casted to a particular type
* No RTEs :)

Once you use the as operator, you can just do a null check to see if the casting is allowed… as below

var btn:Button = new Button;

var lst:List;

lst = btn as List;

if (! lst) {mx.controls.Alert.show(”Sorry you cant cast it this way”); }

But a word of caution. You cannot use the as operator to cast between types in the Top Level classes (to view them , go to the flex language reference). Which means… Say you want to cast a String to a Number, you cannot do,

num = str as Number;

This gives the following error

Implicit coercion of a value of type Number to an unrelated type String

You’ll have to do the age-old way of casting

num = Number(str);

Hope this is useful… at least to beginners


Responses to “Casting Vs The “as” operator”

1. IanT Says:
July 27th, 2007 at 12:07 pm

As an aside - the other use for ‘as’ is for casting to Array.

Because (for historical reasons, I imagine) this:

var a:Object=[1];
var b:Array=Array(a);

results in b being [[1]] (i.e. the Array() operator creates a new array, instead of casting).

In AS2, this was very difficult to get around. In AS3, just use ‘as’:

var a:Object=[1];
var b:Array=a as Array;

No comments: