views:

172

answers:

1

Hey there!

I have an object with a Property of type byte[,,*]

now i'd like to use System.Random::NextBytes() to fill this multidimensional array with random values. NextBytes however takes an argument of byte[]

can i cast the multidimensional array somehow to the singledimensional one in order to pass it as an argument?

thanks!

+3  A: 

You can't cast it, but you can copy the values quickly from a normal byte[] to a byte[,,] using Buffer.BlockCopy. So you'll have to allocate a normal byte array to start with, then copy the results over.

Sample:

using System;

class Test
{
    static void Main()
    {
        Random rng = new Random();
        byte[,,] y = new byte[2,2,2];
        FillArray(y, rng);

        foreach (byte b in y)
        {
            Console.WriteLine(b);
        }
    }

    static void FillArray(byte[,,] array, Random rng)
    {
        byte[] tmp = new byte[array.Length];
        rng.NextBytes(tmp);
        Buffer.BlockCopy(tmp, 0, array, 0, tmp.Length);
    }
}
Jon Skeet
i see - thank you!
Nice answer. Clever.
AMissico