tags:

views:

898

answers:

6

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

A: 

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.

Andrew Hare
StringWriter doesn't write to a file. It writes into memory.
Jon Skeet
Agreed with @Jon Skeet. Maybe you're thinking its base class, TextWriter.
strager
Ah - good catch!
Andrew Hare
A: 

See this...

(CW'ed coz Jon did all the work)

StingyJack
Community Wiki'ed
ChrisF
A: 

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())

abatishchev
Your last paragraph applies to the String*Builder*, not the StringWriter.
Konrad Rudolph
Hmm.. MSDN said that "StringWriter Class implements a TextWriter for writing information to a string" http://msdn.microsoft.com/en-us/library/system.io.stringwriter.aspx
abatishchev
A: 

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.

Konrad Rudolph
A: 

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.

See StringWriter on MSDN

Rob Haupt
I think you're thinking of StringReader rather than StringWriter.
Jon Skeet
+10  A: 

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.

Jon Skeet
+1: First answer to actually address the question. Piped at the post again though, well done Jon
Binary Worrier
Oh, course, Jon comes to save the day. =]
strager