Equivalent of StringBuilder for byte arrays Equivalent of StringBuilder for byte arrays arrays arrays

Equivalent of StringBuilder for byte arrays


Would MemoryStream work for you? The interface might not be quite as convenient, but it offers a simple way to append bytes, and when you are done you can get the contents as a byte[] by calling ToArray().

A more StringBuilder-like interface could probably be achieved by making an extension method.

Update
Extension methods could look like this:

public static class MemoryStreamExtensions{    public static void Append(this MemoryStream stream, byte value)    {        stream.Append(new[] { value });    }    public static void Append(this MemoryStream stream, byte[] values)    {        stream.Write(values, 0, values.Length);    }}

Usage:

MemoryStream stream = new MemoryStream();stream.Append(67);stream.Append(new byte[] { 68, 69 });byte[] data = stream.ToArray();  // gets an array with bytes 67, 68 and 69


The MemoryStream approach is good, but if you want to have StringBuilder-like behavior add a BinaryWriter. BinaryWriter provides all the Write overrides you could want.

MemoryStream stream = new MemoryStream();BinaryWriter writer = new BinaryWriter(stream);writer.Write((byte)67);writer.Write(new byte[] { 68, 69 });


Probably List<byte>:

var byteList = new List<byte>();byteList.Add(42);byteList.AddRange(new byte[] { 1, 2, 3 });