Boaz
Boaz

Reputation: 5084

avoiding passing offset to C# MemoryStream write

I have a MemoryStream object that is getting passed around from function to function, and each function adds something to it (could be byte could be more).
There are matching functions in read.

Can I avoid updating the offset by myself and let "the stream" handle it?
(such as stream.Write(byte[]); similar to stream.WriteByte(byte);)

I'm a bit confused from all the documentation in the area

Upvotes: 1

Views: 2228

Answers (2)

laszlokiss88
laszlokiss88

Reputation: 4071

Yes, you can create an extension method that always sets the offset to 0(i.e. writes from the zero index in the buffer).

public static class Extensions
{
    public static void Write(this MemoryStream stream, byte[] buffer)
    {
        stream.Write(buffer, 0, buffer.Length);
    }
}

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109557

Yes, you can avoid passing the offset around.

When you write to a memory stream, its Position property is incremented by the size of the item(s) written, so the next one written will be after the previous one.

You can therefore just pass around the memory stream.

Upvotes: 1

Related Questions