stevenvh
stevenvh

Reputation: 3159

How are these two ways of typecasting in ActionScript 3 different?

In the Lynda.com title "ActionScript 3.0 in Flash CS3 Professional - Beyond the Basics" Todd Perkins shows how one way of typecasting

var xml: XML;
xml = event.target.data as XML  

doesn't work, while

var xml: XML;
xml = XML(event.target.data)  

does. Shouldn't both forms act the same way? How are they different?
TIA
Steven

edit
declarations added to the code

Upvotes: 1

Views: 563

Answers (2)

splash
splash

Reputation: 13327

The as operator returns null if the left operand (event.target.data) is not an instance of the right operand (expected type = XML), whereas the typecast results in an exception in this case.

Upvotes: 1

Ryan
Ryan

Reputation: 264

Basically they are different by XML(event.target.data) meaning "cast this to that type" where event.target.data as XML means "pretend it is XML".

The former is the same casting that you would expect in other languages like Java. It's a useful way to have code not need to have a try-catch block around a cast. Using as will either return the the first operand if it is the correct type or null otherwise.

You should take a look at the as operator if you need more information.

Upvotes: 4

Related Questions