Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Create an array, then mass allocate variables

Tags:

arrays

c#

Is it possible to do something like

    byte[] byteArray = new byte[100]
    byteArray = {0x00, 0x01, 0x02, 0x03, ... , 0x10}

and then set the rest of the variables later?
I would rather avoid using:

    byteArray[0] = 0x00;
    byteArray[1] = 0x01;

and so on

Sorry, I should have made it more clear that I want to set maybe half the values at once, then fill the rest in later. I'll go with a list

like image 408
Ced Avatar asked Jul 25 '12 12:07

Ced


Video Answer


2 Answers

If you mean can you create an array of 100 items and set 5 of them in-line, something like:

int[] i = new int[100] { 1, 2, 3, 4, 5 };

Then no, you'll get a compiler error:

An array initializer of length '100' is expected.

However, you can do in-line initialization of all items:

int[] i = new int[] { 1, 2, 3, 4, 5 };

Or more tersely (the compiler can infer this as an int[]):

var i = new[] { 1, 2, 3, 4, 5 };

A half-way house is to instead use a list, which can grow in size later:

var i = new List<int> { 1, 2, 3, 4, 5 };
i.Add(6); // etc

Then you can change this to an array as needed:

var iArray = i.ToArray();

There are loads of alternatives, but without knowing much about where these values are coming from, I'm hesitant to keep listing them.

like image 71
Adam Houldsworth Avatar answered Sep 29 '22 05:09

Adam Houldsworth


Yes you can use the array initialization syntax.

byte[] byteArray = new byte[] { 0x00, 0x01, 0x02, 0x03, ... , 0x10};
like image 23
Daniel A. White Avatar answered Sep 29 '22 05:09

Daniel A. White