C# console app System.StackOverflowException' was thrown on big list/array

I trying to write a simple console app for a friend that want to use it for lottery. The app is working fine on small list but as the list grows, it became slower and finally it throws overflow exception. When the list length is less than 5.000, it works fine.

The app asks for starting ticket number, ending ticket number and winning numbers. Then it takes rnadom numbers of the list and delete them so no dublicates occur.

As i understand, the problem is not the length of the list, but the method that select the number from the list and removes right after.

enter image description here

You can see the code here:
dotnetfiddle script

The console app is compiled with .net 4.8

>Solution :

Use a loop instead of recursion, and only call .ToList() once for the array

public static int GetNumber(int[] arr) 
    return GetNumber(arr.ToList());
public static int GetNumber(List<int> list)
    while (list.Count > 1)
        //Remove random number from list
        list.RemoveAt(random.Next(0, list.Count));

    return list[0];

Leave a Reply