Karch said:
Can someone give me the one paragraph answer to when and why I should use
each of the following classes (versus each other):
StreamReader/Writer
StringReader/Writer
TextReader/Writer
BinaryReader/Writer
The first two, in particular, seem to do much of the same thing and both
work with characters. Also, the StringReader seems unnecessary since all it
does is use a StringBuilder - why not just use StringBuilder?
First thing to do is establish what kind of data resource you're
dealing with. If it's a binary resource, then use a Binary* and we're
done.
Next thing to note is that Text* is an _abstract_ base class for
Stream* and String*, so you would only use Text* as a formal parameter
type in something like a general routine that doesn't care what it's
reading from.
If it's a stream that we're read/writing text from/to, we use a Stream*
If it's a string that we're read/writing text from/to, we use a String*
As you note, these two are pretty similar (which is why they share a
base class where much of their behaviour ceontract is defined). The
point of the String* (and indeed of the Text* base class) is that it
allows us to treat a simple string as the source/destination of
arbitrary read/write operations.
Suppose we have some method that is going to produce some text as a
byproduct of its normal operation. What's the best way for the method
to give its caller that text?
- a by-reference String parameter? OK, but there could be a lot of
text, and maybe we want to dump it out to a file or a network as we go
along. So maybe...
- a writable Stream? OK but then for just little calls we still have to
produce a target file or memory stream, so the ideal solution is
- a TextWriter. Now the caller can either supply a StringWriter or a
StreamWriter as appropriate to *its* needs; and the method itself, when
it wants to _write_ _text_, can just do so to this clearly appropriate
object - a TextWriter.