8bitcartridge 8bitcartridge -4 years ago 173
C# Question

C# - Can I use an array initializer to build one byte array out of another?

I'd like to use an array initializer to build one byte array out of another byte array as well as some other bytes that form a header/trailer. Basically, I'd like to do something like this:

byte[] DecorateByteArray(byte[] payload)
return new byte[] { 0, 1, 2, payload.GetBytes(), 3, 4, 5};

above is fictional, unfortunately.

Is there any nice/elegant way to do this? I solved this by using a
to write everything to a
, and then converting this into a byte array with
, but it feels kind of clunky.

Answer Source

The closest you could get would be:

byte[] DecorateByteArray(byte[] payload) =>
    new byte[] { 0, 1, 2 } 
       .Concat(new byte[] { 3, 4, 5 })

That would be pretty inefficient though. You'd be better off doing something like:

static T[] ConcatArrays<T>(params T[][] arrays)
    int length = arrays.Sum(a => a.Length);
    T[] ret = new T[length];
    int offset = 0;
    foreach (T[] array in arrays)
        Array.Copy(array, 0, ret, offset, array.Length);
        offset += array.Length;
    return ret;

(Consider using Buffer.BlockCopy too, where appropriate.)

Then call it with:

var array = ConcatArrays(new byte[] { 0, 1, 2 }, payload, new byte[] { 3, 4, 5 });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download