Search code examples
c#stack-overflow

Stack overflow error in loop function


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
}

Solution

  • You should be doing this in a loop, not using recursion. Each time you recurse it's going to add information to the stack and eventually you'll run out of stack space. In this case, you're recursing infinitely. (You're not stopping it from recursing if number > maxnumber).

    void LoadFavorites()
    {
        int number = 1; 
        int maxnumber = 10000; 
        while (number <= maxnumber)
        {
           if (Properties.Settings.Default.FavoriteList.Contains("'"+number+"'"))
           {
               this.listBox1.Items.Add(number);
           }
           number = number + 1;
        }
    }
    

    (edit: additional comment about "'"+number+"'" removed)