Amit
Amit

Reputation: 22076

How to increase byte[] size at run time?

I have to increase byte[] array size at runtime.
How to increase byte[] array size at run time ?

Upvotes: 28

Views: 49170

Answers (6)

Paolo Guccini
Paolo Guccini

Reputation: 57

if your byte array is used to collect data and grow with it, you can use the class: System.IO.MemoryStream (here link to microsoft class description)

Upvotes: -1

sehe
sehe

Reputation: 392911

Why does no one seem to know Array.Resize:

 Array.Resize(ref myArray, 1024);

Simple as pie.

PS: _as per a comment on MSDN, apparently this was missing from the MSDN documentation in 3.0.

Upvotes: 75

Kevin
Kevin

Reputation: 5694

You could allocate a new array and copy the bytes over with Array.Copy(..)

byte[] oldArr = new byte[1024];
byte[] newArr = new byte[oldArr.Length * 2];

System.Array.Copy(oldArr, newArr, oldArr.Length);

oldArr = newArr;

Upvotes: 7

Richard
Richard

Reputation: 108975

You can't: arrays are fixed size.1

Either use a re-sizable collection (eg. List<byte>) or create a new larger array and copy the contents of the original array over.


1 Even Array.Resize doesn't modify the passed array object: it creates a new array and copies the elements. It just saves you coding this yourself. The difference is important: other references to the old array will continue to see the old array.

Upvotes: 17

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60694

A array is of fixed size, and cannot be dynamically changed at runtime.

Your only option is to create a new array of the wanted size, and copy all bytes from the old array to the new one.

But why torture yourself with this instead of using List<byte> and simply adding or removing elements at will?

Upvotes: 2

leppie
leppie

Reputation: 117220

If you have to increase it, why not start off with a List<byte> in the first place?

Upvotes: 3

Related Questions