StringWriter or StringBuilder

Viewed 34821

What is the difference between StringWriter and StringBuilder and when should I use one or the other?

7 Answers

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.

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.

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, As far as i know, then String.Concat(). Also it can be used with specific format (.AppendFormat())

Related