views:

50

answers:

2

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

+1  A: 

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.

splash
`xml` is declared as an XML type. Indeed, the `as` form returns `null`, but the second form returns the XML data from the URLLoader.
stevenvh
Where this answer says "left operand", it's referring to `event.target.data`, not to `xml`.
fenomas
I'm curious what the downvote is for?
splash
+3  A: 

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.

Ryan