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 Java, you can’t define implicit conversions between types anyway, beyond what’s in the specification – so you can’t convert from
StringBuildertoStringanyway; you have to calltoString().In C# there could be an implicit user-defined conversion between
StringBuilderandString(defined in eitherStringBuilderorString), but there isn’t – so you still have to callToString().In both cases you will get a compile-time error if you don’t call the relevant method.