2

What is the best method to add two bytes into a existing bytes array?

Should I use Array.Copy?

Alvin
  • 8,219
  • 25
  • 96
  • 177
  • 1
    Can you be more specific? Are you asking about increasing the number of elements in the array? Where do you want to "add" the two bytes? – John Saunders Jul 20 '12 at 02:30
  • Given the meaning of "Add" in the `ICollection` interface, the answer to you question is no. You cannot increase the size of an array; you can only replace it with a different, larger array (as user1501472 suggests). If you need the same object to grow, you should use a List, as user1501472 suggests in a separate answer. – phoog Jul 20 '12 at 03:51
  • If this is just one time operation, then use Array.Copy(). If it is repetitive, use List. – Shakti Prakash Singh Jul 20 '12 at 07:15
  • @Kelvin Follow up: if this question is answered, please either choose one of the answers or update the question to share your solution. – Andre Calil Jul 24 '12 at 05:09

3 Answers3

2

Well, this is an interesting subject. I've made a microbenchmark and, yes, the fastest way is using Array.Copy.

Check this out: Prepend to a C# Array

Regards

Community
  • 1
  • 1
Andre Calil
  • 7,652
  • 34
  • 41
2

Use a List instead of a byte[]; it will provide the flexibility and it is good performance wise

List<byte> l1 = new List<byte>() { 5, 6, 7, 10, 11, 12 };  
List<byte> l2 = new List<byte> { 8, 9 };
l1.InsertRange(3, l2);

Then if you need to go back to a byte[] for whatever reason you can call...

l1.ToArray();
Simon
  • 33,714
  • 21
  • 133
  • 202
NG.
  • 5,695
  • 2
  • 19
  • 30
0

or else

byte[] newArray = new byte[theArray.Length + 1];  
theArray.CopyTo(newArray, 1);  
newArray[0] = theNewByte;  
theArray = newArray;
Simon
  • 33,714
  • 21
  • 133
  • 202
NG.
  • 5,695
  • 2
  • 19
  • 30
  • You should probably combine this with your other answer. "or else" doesn't always make sense as your two answers can appear in any order (they are not sorted by when they were written). – Jim D'Angelo Jul 20 '12 at 03:01
  • actually i meant to add the comment for my 1st post, but added another post by mistake. – NG. Jul 20 '12 at 03:04
  • 1
    @user1501472 then you can edit your first answer to add the content of your second answer to it, and then delete the second answer. – phoog Jul 20 '12 at 06:53