hi there,

i want to randomly pick an element from an array, so i used the following code.

Random rndCell = new Random((int)DateTime.Now.Ticks);

while (true)
{
    rndCell.Next(aCells.Length);
    int rndIndex = Convert.ToInt32(rndCell.ToString());
    if (aCells[rndIndex] != null)
    {
        aCells[rndIndex] = SOMETHING;
        // DO SOMETHING ELSE WITH rndIndex...
        break;
    }
}

it raises an error while trying to convert the random number to integer. does anyone knows how to do it?

best regards,
Sean

Most of the time you do not want to provide a seed to a random number generator. This will have the same effect as your code:
Random rndCell = new Random();
Line 5 and 6 can be replaced with this :
int rndIndex = rndCell.Next(aCells.Length-1);
If your array has a lenght of 10, this will produce numbers from 0 to 9! (The indexes of your array! Not 0 to 10, 10 is not an index!)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.