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
?StringWriter Class Implements a TextWriter for writing information to a string and the information is stored in an underlying StringBuilder Class. StringBuilder Class Represents a mutable string of characters and this class cannot be inherited.
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.
StringReader enables you to read a string synchronously or asynchronously. You can read a character at a time with the Read or the ReadAsync method, a line at a time using the ReadLine or the ReadLineAsync method and an entire string using the ReadToEnd or the ReadToEndAsync method.
public class StringWriter extends Writer. A character stream that collects its output in a string buffer, which can then be used to construct a string. Closing a StringWriter has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With