8

I need a C# implementation of something similar with ByteBuffer from Java. Methods of interest - .remaining() - returns the number of elements between the current position and the limit. - .array() - .clear() - .put(byte[], int, int)

I started something with MemoryStream.. but no clear(), and a lot of improvisation Also, i found a c# implementation on Koders: http://www.koders.com/csharp/fid2F8CB1B540E646746D3ADCB2B0AC867A0A8DCB06.aspx?s=socket#L2.. which I will use.. but maybe you guys know something better

2
  • 1
    put->Write, clear->Position=0, array()->ToArray() etc. I can't see what you can't do with MemoryStream. Commented Apr 9, 2012 at 19:26
  • 1
    @L.B, setting Position to 0 is not equivalent to clear... but SetLength(0) would be Commented Apr 9, 2012 at 19:32

3 Answers 3

33

MemoryStream can do everything you want:

  • .array() => .ToArray()
  • .clear() => .SetLength(0)
  • .put(byte[], int, int) => .Write(byte[], int, int)
  • .remaining() => .Length - .Position

If you want, you can create extension methods for Clear and Remaining:

public static class MemoryStreamExtensions
{
    public static void Clear(this MemoryStream stream)
    {
        stream.SetLength(0);
    }

    public static int Remaining(this MemoryStream stream)
    {
        return stream.Length - stream.Position;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

What about ByteBuffer.allocate(int) ?
@Paul, new MemoryStream(int)
3

MemoryStream should have everything you are looking for. Combined with BinaryWriter to write different data types.

var ms = new MemoryStream();
ms.SetLength(100);

long remaining = ms.Length - ms.Position; //remaining()

byte[] array = ms.ToArray(); //array()

ms.SetLength(0); //clear()

ms.Write(buffer, index, count); //put(byte[], int, int)

Comments

-4

Are you looking for a Queue<T>?

http://msdn.microsoft.com/en-us/library/7977ey2c.aspx

For some of the methods that Queue doesn't support, it might be easy enough to write a custom class that wraps a Queue.

1 Comment

Queue only allows adding and removing single elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.