views:

213

answers:

3

How would I go about writing my own stream manipulator class?

Basically what I'm trying to wrap my head around is storing the reference to the underlying stream in the writer. For example, when writing to a memory stream using a StreamWriter, when a Write() is made, the underlying memory stream is written to.

Can I store the reference to an underlying stream without using pointers or unsafe code? Even if it was just a string I wanted to "write" to.

Really this has little to do with stream writers, and I'm just wondering how I could store references in a class. The StreamWriter was the best example I could come up with for this.

+1  A: 

No unsafe code is needed. Check out this example I put together.

public sealed class StreamManipulator
{
    private readonly Stream _backingStream;

    public StreamManipulator(Stream backingStream)
    {
        _backingStream = backingStream;
    }

    public void Write(string text)
    {
        var buffer = Encoding.UTF8.GetBytes(text);
        _backingStream.Write(buffer, 0, buffer.Length);        
    }
}
ChaosPandion
A: 

Classes are reference types in C#, so yes, what you have is always a reference (a managed pointer) to the actual class data, stored "somewhere" in memory.

500 - Internal Server Error
A: 

sure you can. Just declare a property of type Stream and assign some value to it. If you post some code you could get a bit clearer answer. Here's a sample though.

class foo { public MemoryStream MyMemory { get; set; }

public void Write(string s)
{
    MyMemory.Write(System.Text.Encoding.ASCII.GetBytes(s));
}

[STAThread]
static void Main()
{
    foo f = new foo();
    f.MyMemory = new System.IO.MemoryStream();

    f.Write("information");
}

}

gbogumil