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
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With