Dark Side
Dark Side

Reputation: 715

Indirect Initialization of multidimensional array in C#

I am trying to indirectly initialize an byte[,] by not specifying the bytes sicne the should be chosen randomly.

 byte[] First = BitConverter.GetBytes(rnd.Next(10000, 90000));
            byte[] Second = BitConverter.GetBytes(rnd.Next(10000, 90000));
            byte[] Third = BitConverter.GetBytes(rnd.Next(10000, 90000));
            byte[] Fourth = BitConverter.GetBytes(rnd.Next(10000, 90000));
            byte[] Fifth = BitConverter.GetBytes(rnd.Next(10000, 90000));
            byte[] Sixth = BitConverter.GetBytes(rnd.Next(10000, 90000));
            byte[] Seventh = BitConverter.GetBytes(rnd.Next(10000, 90000));
            byte[] Eighth = BitConverter.GetBytes(rnd.Next(10000, 90000));

            byte[,] Arr2D = new byte[,] { First, Second, Third, Fourth, Fifth, Sixth, Seventh, Eighth };

This is how I planned to do it, but there is a problem: It's not possible to initialize a byte[,] like so.

And I cannot specify static values for the arrays, so creating nested arrays is not possible.

What would be the correct way to initialize a byte[,] with random values like shown above?

Upvotes: 1

Views: 131

Answers (1)

Alexandre Perez
Alexandre Perez

Reputation: 3495

If I understand right your question maybe this will do the job:

var rnd = new Random();
var Arr2D = new byte[8,4]; // 8 rows and 4 (BitConverter.GetBytes give us an array of bytes with length 4). 
for (var i = 0; i < 8; i++)
{
    var sequence = BitConverter.GetBytes(rnd.Next(10000, 90000));
    for (int j = 0; j < sequence.Length; j++)
    {
        Arr2D[i, j] = sequence[j];
    }
}

Upvotes: 1

Related Questions