Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the StringBuilder class inherited from Stream?

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.

like image 503
Deane Avatar asked Nov 28 '22 08:11

Deane


2 Answers

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.

like image 192
Jon Skeet Avatar answered Nov 29 '22 22:11

Jon Skeet


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.

like image 44
Brian Ensink Avatar answered Nov 29 '22 23:11

Brian Ensink