FoppyOmega
FoppyOmega

Reputation: 447

How to create a byte[] of unknown size in C#?

I'm trying to create a byte[] given some unknown amount of bytes. Here's an example:

ArrayList al = new ArrayList();
al.Add(0xCA);
al.Add(0x04);
byte[] test = (byte[])al.ToArray(typeof(byte));

I'm receiving an error that one or more of the values in the array cannot be converted to a byte. What am I doing wrong here?

Thanks

Upvotes: 4

Views: 2396

Answers (3)

Brian
Brian

Reputation: 25834

Either use a generic collection instead of a nongeneric ArrayList, or make sure you are actually using bytes. 0xCA is an int, not a byte.

        ArrayList al = new ArrayList();
        al.Add((byte)0xCA);
        al.Add((byte)0x04);
        byte[] test = (byte[])al.ToArray(typeof(byte));

Upvotes: 9

Taylor Leese
Taylor Leese

Reputation: 52300

Use List<byte> like below. When you are using ArrayList and then calling al.Add(0xCA) you are actually adding int's to the ArrayList.

List<byte> al = new List<byte>();
...

Upvotes: 0

Steve Mitcham
Steve Mitcham

Reputation: 5313

Try List<byte> and then use ToArray

Upvotes: 11

Related Questions