StringBuilder Vs StringWriter/StringReader

SaravananArumugam picture SaravananArumugam · Aug 3, 2010 · Viewed 23k times · Source

I recently read that in StringWriter and StringReader are used for writing and reading from StringBuilder.

Well when I use StringBuilder Object, it looks to be a self sufficient class.

We have every way of reading and writing the StringBuilder, using StringBuilder.Append(), Insert(), Replace(), Remove() etc...

  1. What is the possible use of StringWriter and StringReader, which cannot be done by StringBuilder itself?
  2. What is the practical use of them?
  3. What could be the possible reason they are not taking up Stream as the input (Because any other writer and reader are taking the stream as the Constructor parameter to operate on) but the StringBuilder?

Answer

Greg Beech picture Greg Beech · Aug 3, 2010

What is the possible use of StringWriter and StringReader, which cannot be done by StringBuilder itself?

StringReader and StringWriter derive from TextReader and TextWriter respectively. So what they can do act as a TextReader or TextWriter instance, which string or StringBuilder cannot because they do not derive either of those types.

What is the practical use of them?

They allow you to call APIs that are expecting a TextReader or TextWriter, when what you have/want is a string or StringBuilder.

What could be the possible reason they are not taking up Stream as the input (Because any other writer and reader are taking the stream as the Constructor parameter to operate on) but the StringBuilder?

Because they don't work on streams; they work on strings or StringBuilders. They're just simple wrapper classes that adapt these types for APIs expecting a different interface. See: adapter pattern.