I'm pretty new to c# and I'm trying to make a function that checks if a certain number is in a list, and I want to run the function for every number between 1-10000. Currently it looks like this but i'm getting System.StackOverflowException so does anyone know how to do this correctly?
int number = 1;
int maxnumber = 10000;
void LoadFavorites()
{
if (number <= maxnumber)
{
if (Properties.Settings.Default.FavoriteList.Contains("'"+number+"'"))
{
this.listBox1.Items.Add(number);
}
}
// Increases number by 1 and reruns
number = number + 1;
LoadFavorites(); // problem is probably here
}
You are right. You have a recursive function there that does not have an appropriate stopping condition. Maybe you need a loop that goes from 1 to 100000 instead and there you call the function loadFavorites(). The stackoverflow is caused because you are calling loadFavorites() an infinite number of times, eventually you run out of stack space.
e.g.
for(int i=number; i<maxNumber; i++)
{
if (Properties.Settings.Default.FavoriteList.Contains("'"+i+"'"))
{
this.listBox1.Items.Add(i);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With