What is the difference and when should I use one or the other?
A StringWriter
is used to write text to a file memory and a StringBuilder
is used to append strings together in a memory-efficient manner.
StringBuilder
is used to mass string concatenation. It's more effective for more then 5 string, AFAIK, then String.Concat()
. Also it can be used with specific format (.AppendFormat()
)
The StringBuilder
class is basically a mutable string, a helper class to construct an immutable string. The StringWriter
is built on top to add more convenience functions for string formatting.
Use StringBuilder if you are working with a string within your code.
Use StringWriter to serve up text within your code.
I would use StringBuilder for writing of strings and StringWriter for the reading of the strings within your code.
StringWriter
derives from TextWriter
, which allows various classes to write text without caring where it's going. In the case of StringWriter
, the output is just into memory. You would use this if you're calling an API which needs a TextWriter
but you only want to build up results in memory.
StringBuilder
is essentially a buffer which allows you to perform multiple operations (typically appends) to a "logical string" without creating a new string object each time. You would use this to construct a string in multiple operations.