views:

848

answers:

6

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.

+6  A: 

A stream normally refers to an external input/output source (file, network). StringBuilder has no such characteristic.

Otávio Décio
+1 ... I was in the process of writing an answer eerily similar to this... :D
Daniel Schaffer
I think all of us were.
Kyle Trauberman
+3  A: 

Because it's not really a stream. It's more of a buffer that grows.

Joel Coehoorn
+1  A: 

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.

Kyle Trauberman
+10  A: 

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.

Brian Ensink
+8  A: 

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.

Jon Skeet
+1  A: 

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...

flq