Click here to Skip to main content
15,882,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I know we can convert a string builder to string using toString() and new String(stringbuilder) functions and constructor.. But I want to know the reason why this statement raises an error as "StringBuilder cannot be converted to String"
String s = (String) StringBuilder;

What I have tried:

Convert stringbuilder to string using string literal
Updated 14-Feb-18 1:07am

Because a StringBuilder is a different class, and cannot be directly used as a String. You must use the toString() method, as described in the documentation.
Share this answer
There is no such thing as a StringBuilder to String conversion.
StringBuilder class provides you with a toString method which allows you to get the string which is actually stored in the internal buffer of the StringBuilder object.
You have to use
String s = sb.ToString();
, sb being a variable of the StringBuilder class.
// Bad code!
String s = (String)StringBuilder;

is not correct on at least two levels:

  • You cannot cast a StringBuilder variable to a string directly.
  • StringBuilder is a class, not a variable. You cannot cast a class to anything, you only cast variables.
Share this answer
Well, I guess in case of type casting you'll have to take check for the "IS-A" test which would fail in this case as StringBuilder is NOT a String. In case of conversion you explicitly have to use the "toString()"(note that 't' isn't capital).
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900