C #: create an array, then mass distribution of variables

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 prefer to avoid using:

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

etc.

Sorry, I should have made it clearer that I want to set maybe half the values ​​right away, and then fill in the rest later. I'll go with the list

+5
source share
5 answers

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

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

Then no, you get a compiler error:

An array initializer of length 100 is expected.

However, you can initialize all the elements in the line:

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

Or more complicated (the compiler can do it like this int[]):

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

, :

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

:

var iArray = i.ToArray();

, , , , .

+4

, .

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

100 , . , :

byte[] byteArray = new byte[100];   
byte currentByte = 0x00;
for (int i = 0; i < byteArray.Length; i++)
    byteArray[i] = currentByte++;

256 , , , . , script #:

byte[] byteArray = new byte[256];
byte currentByte = 0x00;
for (int i = 0; i < byteArray.Length; i++)
    byteArray[i] = currentByte++;

Console.Write(String.Format("byte[] byteArray = new byte[{0}] {{", byteArray.Length));
Console.Write(String.Join(", ", byteArray));
Console.Write("};");

/ #.

EDIT: . , 256, currentByte 0, .

+1

, , , - , .

List<byte> byteArray = new List<byte>() { initialize what you want here };
...
...
byteArray[*n*] = *value*
...
...
byteArray.Add(*value*);

It is much more flexible. With a list of bytes, you can add everything to it whenever you want and set it with an indexer as long as the index exists. Alternatively, you can make this list an array using the following line of code.

byteArray.ToArray();

It returns byte[*length of list*]

+1
source

If you know how many elements you want to initialize first, you can create a dictionary initializer. Example:

Dictionary<int,byte> initializer = new Dictionary<int,byte> { {0, 0x01}, {3, 0x04}, {7, 0xFF} .. };

Then pre-initialize the empty array with a simple loop:

byte[] byteArray = new byte[100];

foreach (int key in initializer.Keys)
  byteArray[key] = initializer[key];
0
source

All Articles