I have been working with streams the last couple of days and they were confusing at first, especially the way C# does it differently to Java.

With the help of MSDN and nearby kind craftspeople, it's beginning to become clearer.

We will use a simple example to explain how they work.

Let say we want to create a console that reads and writes to a stream. Luckily for us in C# we have a handy class called 'MemoryStream' which shockingly creates a stream.

We can pass this MemoryStream into our constructor like so

public AwesomeConsole (MemoryStream stream) {
this.stream = stream;
}

We are assigning it to a private field here so we can use it later in our read and write methods.

Lets move on to the Read method.

public string Read () {
var streamReader = new StreamReader (stream);
return streamReader.ReadToEnd ();
}

Here we are using the 'var' keyword which does away for the need for explicitly type declarations which is quite nice (not at the time though)

We instantiate a new StreamReader object, passing a 'Stream' to it's constructor.

The StreamReader class reads characters from a byte stream, depending on the characters that you're willing to accept, you may have to include a require Encoding such as UTF8Encoding. For the sake of simplicity we won't doing that.

Streams are like old fashion cassette tapes( go further back, Betamax tapes), in that we can rewind them, fast forward to a moment in the stream. In this case we want to read to the end of the stream using the appropriately name method 'ReadToEnd' which returns us our string object.

Tomorrow will be part 2... writing to streams.

Ced

Ced