NateS NateS - 1 year ago 44
C# Question

IndexOutOfRange exception - help me please


I can't understand what's wrong.. help please.

static int WinningColumn()
Random rnd = new Random(46);

int[] winningnumbers = new int[6];
int[] Check = new int[46];
int i;
for (i = 0; i < winningnumbers.Length; i++)
winningnumbers[i] = rnd.Next(46);

if (Check[winningnumbers[i]] > 1)

the error happens here..

return winningnumbers[i];

Answer Source

When you exit from the for loop the indexer variable i has a value bigger than the max index possible (It is the condition that breaks the loop).
In your case the variable i has the value of 6 but the max index possible for the array winningnumbers is 5. (0 to 5 are six integer elements).

It is not clear what is your intent but supposing that your purpose is to generate six winning numbers ranging from 0 to 45 then your code should be rewritten and simplified in this way

static List<int> WinningColumn()
    // Do not initialize Random with a fixed value
    // You will get always the same 'random' sequence
    Random rnd = new Random();

    // Create a list to store the winners
    List<int> winningnumbers = new List<int>();
    int i = 0;
    while(i < 6)
        int newNumber = rnd.Next(46);
            // If the list doesn't contain the number the add it and increment i
            // Otherwise run the loop again....

    // This returns the whole list to the caller, 
    // you can use it as an array 
    return winningnumbers;

Notice that your actual code contains a bug in the declaration of the Random number generator. You pass an initial seed and thus, everytime you call this method, the random generator starts again with the same sequence of numbers. The result would be an identical list of numbers. Not very random to me
If you don't pass anything then the generator is initialized with the system time and thus should be different every time you call this method.