Search code examples
c#stack-overflow

Keep Checking A Value Without Stack Overflow


For a small C# Windows forms project I'm working on, I need to ask a simple Y/N question. I need it to repeat until it is given the correct value. If I use this code, it creates a stack overflow:

    void Intro()
    {

        if (input == "YES" || input == "Y")
        {
          //Do Stuff
        }
        else
        { 
            Intro();
        }
    }

I looked around and apparently the best way to handle this is with a while loop. So I try using this code, which results in the form not loading when I compile and run:

    void Intro()
    {
        while (true)
        {
            if (input == "YES" || input == "Y")
            {
              //Do Stuff
            }
        }
    }

It doesn't give any errors, and runs until I stop it. The method is run right after InitializeComponent. This is probably a really stupid question, so sorry if it could be answered in a few seconds.


Solution

  • You should put the checking in an event; it doesnt necessarily have to be a button click event.

    private void button_Click(object sender, EventArgs e)
    {
         if(input=="YES" || input=="Y")
            //do stuff
         else
            //reshow question
    }