5

When I was writing some I/O routine in C++, I would usually make it as generic as possible, by operating on the interfaces from <iostream>.

For example:

void someRoutine(std::istream& stream) { ... }

How should the same be done in C#?

I suspect I could write my routines based on the System.IO.TextReader or System.IO.TextWriter, but I'm not sure.


Obviously I'm seeking for a same base class in C#, which is as generic as std::istream or std::ostream and which can be extended in many ways (for example, as boost::iostreams extends the std:: streams).

George Johnston
  • 31,652
  • 27
  • 127
  • 172
Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148
  • 1
    An abstract class is about as basic as you're going to get... (though depends what you're looking for, too; there's also [System.IO.Stream](http://msdn.microsoft.com/en-us/library/system.io.stream.aspx)) – Brad Christie Feb 07 '11 at 19:13

4 Answers4

5

If you want to work with strings, you should take a TextReader or TextWriter.

If you want to work with bytes, you should take a Stream.

These classes are inherited by concrete implementations such as FileStream, StringWriter, and NetworkStream.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    That's not exactly true. TextReader and TextWriter operate on streams, but they are not in the inheritance chain of either Stream or FileStream. They are the bases for StringReader and StringWriter, respectively. For what the OP is looking to do, System.IO.Stream is the appropriate class (equivalent to a combined Input and Output Stream). – Chris Shain Feb 07 '11 at 19:18
  • 1
    @Chris: I never said that. I said _these_ classes. – SLaks Feb 07 '11 at 19:19
  • I misinterpreted your answer then, apologies. I took "These classes" to mean all of the classes mentioned above, I assume the OP could have made the same mistake. – Chris Shain Feb 07 '11 at 19:20
3

Use System.IO.Stream if you only care about bytes. TextReader / TextWriter are for when you know the underlying data to be text.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
1

The base class is Stream. MemoryStream, FileStream, etc. inherit from this class.

George Johnston
  • 31,652
  • 27
  • 127
  • 172
0

You can have the C# function taking a Stream ( System.IO.Stream ) as in C++. If this is appropriate depends on the function you write.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115