Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between String(value) and value as String?

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...

like image 822
Paul Mignard Avatar asked Nov 06 '08 03:11

Paul Mignard


2 Answers

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.

like image 165
Randy Stegbauer Avatar answered Oct 08 '22 15:10

Randy Stegbauer


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

like image 40
RickDT Avatar answered Oct 08 '22 14:10

RickDT