Skip to main content
Venian
Inspiring
February 24, 2012
Answered

What's the difference between String() - as String - toString();

  • February 24, 2012
  • 2 replies
  • 1730 views

Hello,

I'm wondering what's the difference between this 3 ways of getting around.

This topic has been closed for replies.
Correct answer kglad

there's zero difference between casting an object as a string using:

String(something)

and

something as String.

if you can use one of the above on the same object that you're applying the toString() method to, there will be no difference among the 3.

2 replies

Participating Frequently
March 7, 2012

There is a great difference between String(), as String and toString() methods.

String(param) -- the more general and safe method.

  • Returns "null" (string!) if param is null;
  • Returns result of param.toString() method if it is defined in class;
  • Returns string representation of the param (returns "[object Object]" if param is Object);

param asString --

  • Returns string if param is a type of String;
  • Returns null otherway (if param is custom class, int or other type);

param.toString() -- call of toString() member function

  • throws an exception if param is null;
  • compile-time error if toString() method is not defined in param (if your custom class do not have or inherits this function);
  • returns result of toString() function

Exists also ""+param and param+"" ways. They are similar to ""+String(param) and String(param)+""

Pay attention:

var ss:String = null;

trace(String(ss)==(ss as String)); // Returns false as "null" not equal to null

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
February 24, 2012

there's zero difference between casting an object as a string using:

String(something)

and

something as String.

if you can use one of the above on the same object that you're applying the toString() method to, there will be no difference among the 3.

Venian
VenianAuthor
Inspiring
February 24, 2012

I see, but if instead of string there's MyClass or MovieClip...

kglad
Community Expert
Community Expert
February 24, 2012

if there's a difference between the two classes, MyClass and MovieClip, then there might be a difference when casting.