Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does StringBuilder need ToString()

This should hopefully be a quick one. I have a StringBuilder like so:

StringBuilder sb = new StringBuilder();

I append to my StringBuilder like so:

sb.Append("Foo");
sb.Append("Bar");

I then want to make this equal to a string variable. Do I do this like so:

string foobar = sb;

Or like so:

string foobar = sb.ToString();

Is the former being lazy or the latter adding more code than is necessary?

Thanks

like image 867
JMK Avatar asked Nov 30 '22 03:11

JMK


2 Answers

In C# you need to use string foobar = sb.ToString(); or you will get an error: Cannot implicitly convert type 'System.Text.StringBuilder' to 'string'

like image 42
Anders Wendt Avatar answered Dec 04 '22 14:12

Anders Wendt


In Java, you can't define implicit conversions between types anyway, beyond what's in the specification - so you can't convert from StringBuilder to String anyway; you have to call toString().

In C# there could be an implicit user-defined conversion between StringBuilder and String (defined in either StringBuilder or String), but there isn't - so you still have to call ToString().

In both cases you will get a compile-time error if you don't call the relevant method.

like image 194
Jon Skeet Avatar answered Dec 04 '22 13:12

Jon Skeet