Why is the StringBuilder class not inherited from Stream?

I'm just curious. It seems to me that the behavior of StringBuilder is functionally (if not technically) the same as Stream - it is a bit of data to which other data can be added.

Again, just curious.

+4
source share
6 answers

A stream is the input and output of binary data.

StringBuilder is a tool for creating text data.

In addition, there is a state problem - StringBuilder has only the current value, not having the concept of "position". It allows you to receive and modify data anywhere. On the other hand, a stream is a logically potentially endless stream of data with a cursor somewhere in the middle to tell where you should be. Usually you just read / write ahead using Seek / Position to jump to a specific part of the data stream.

Try introducing the Stream API implementation using StringBuilder ... it just doesn't fit. You can do this, but you end up with StringReader and StringWriter.

+10
source

StringBuilder has more than just add functions. It also has insert functions that are unnatural for a stream. Use the StringWriter class if you want a stream that wraps a StringBuilder .

+10
source

A stream usually refers to an external input / output source (file, network). StringBuilder does not have this characteristic.

+6
source

Because it is not a real stream. This is more of a buffer that is growing.

+3
source

While both may have data added, the functionality is generally different.

A stream is designed to input or output data from / to some source, and not to create anything. StringBuilder does not need the functions that Stream provides, such as Buffering, etc. To create a resource.

+1
source

On the other hand, you will find the StringReader / Writer classes in System.IO. StringWriter , for example. implements TextWriter for the underlying StringBuilder .

Personally, I never used it, but if you have a program for writing text files, you can make it work with TextWriter . Then, in your test, instead of creating an instance of StreamWriter, you create an instance of StringWriter , after which you can check what was written by looking at the underlying StringBuilder .

Now I am dizzy ...

+1
source

All Articles