I'm just curious about this. It strikes me that the behavior of a StringBuilder is functionally (if not technically) the same as a Stream -- it's a bin of data to which other data can be added.
Again, just curious.
I'm just curious about this. It strikes me that the behavior of a StringBuilder is functionally (if not technically) the same as a Stream -- it's a bin of data to which other data can be added.
Again, just curious.
A stream normally refers to an external input/output source (file, network). StringBuilder has no such characteristic.
Because it's not really a stream. It's more of a buffer that grows.
While both can have data added to them, the functionality as a whole is different.
A Stream is for inputting or outputting data from/to some source, not for building something. StringBuilder does not need functionality that Stream provides, like Buffering, etc to build a resource.
StringBuilder
has more than just Append functions. It also has insert functions which is unnatural for a stream. Use the StringWriter
class if you want a stream that wraps a StringBuilder
.
Stream is an input and output of binary data.
StringBuilder is means of building up text data.
Beyond that, there's the issue of state - a StringBuilder just has the current value, with no idea of "position". It allows you to access and mutate data anywhere within it. A stream, on the other hand, is logically a potentially infinite stream of data, with a cursor somewhere in the middle to say where you've got to. You generally just read/write forwards, with Seek/Position to skip to a specific part of the data stream.
Try to imagine implementing the Stream API with StringBuilder... it just doesn't fit. You could sort of do it, but you'd end up with StringReader and StringWriter, basically.
On the other hand you will find the classes StringReader/Writer in System.IO. The StringWriter e.g. implements TextWriter against an underlying StringBuilder.
Personally I've never used it but if you have a text file writing routine you could make it work against a TextWriter. Then in your test, instead of instantiating a StreamWriter you instantiate a StringWriter and you could then check what was written by looking at the underlying StringBuilder.
Now I'm dizzy...