views:

332

answers:

2

Just to make this clear - what is the difference between:

String(value)

and

value as String

What are the cases where you would use one over the other? They seem interchangeable...

+10  A: 

Casting with Type(variable) can cause a runtime exeception (RTE), while "variable as type" will return null instead of throwing an exception.

See http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/ for more explanations.

Randy Stegbauer
Thanks for clearing that up!
onekidney
+1  A: 

String (value) creates a new String object from a string literal. If the constructor argument is not a string literal, I assume it calls the argument object's .toString() method.

value as String will simply pass back value IF value is a String or a subclass of String. It will pass back null if value is not of type String.

The important thing to note is that String(val) creates a new object whereas value as String simply refers to value (and tests for compatibility to String).

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/String.html

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/operators.html#as

RickDT
It is not true that the `Type(variable)` syntax necessarily creates a new object. It is not the same as a constructor (though it looks like it). It actually returns a reference to the same object so long as the `variable` is compatible with `Type` (so long as no toString occurs).
aaaidan