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...
StringWriter
and StringReader
, which cannot be done by StringBuilder
itself?Stream
as the input (Because any other writer and reader are taking the stream as the Constructor parameter to operate on) but the StringBuilder
?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 string
s or StringBuilder
s. They're just simple wrapper classes that adapt these types for APIs expecting a different interface. See: adapter pattern.