Friday, March 4, 2011

Casting vs as

   Recently, I ran into a bunch of odd behavior from one of the programs (software, program, application, app?.  I feel like app is a dirty buzzword these days) I had to update  and it took me a while to figure out what went wrong.

The short of the long of it, is that I was using "as"  which resulted in some classes which could not be converted properly to fail.  When using "as" [ as in  myVar:Spite = myMovieClip as Sprite; ] if the conversion fails  you get a null response.  However, if you cast the object you will get a noisy runtime error instead. [ myVar:Sprite = Sprite(myMovieClip); ]

This is another good reason to use interfaces. However if for some reason you are converting class types, but are not using interfaces.. I think it best you know what you are doing.  Cast if it is someone else code, and use as only when you really want the silent null failure.  The difference in performance is negligible outside of a loop or for non gaming programs.