Search code examples
c#stringbuilder

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


Solution

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