Search code examples
c#exceptionstack-overflow

StackOverflowException was unhandled C#


I am getting a odd error that I cant recall ever getting before. I am trying to make a few menus for a small game but somehow something is wrong with my reference to Form1.

Here is the code:

public partial class Form1 : Form
    {
        Form2 Form2 = new Form2();
        Form3 Form3 = new Form3();
        public string difficulty = "Makkelijk";
        public string guesses = "Normaal";

        public Form1()
        {
            InitializeComponent();
        }

        private void playButton_Click(object sender, EventArgs e)
        {
            //Form3.difficulty = difficulty;
            //Form3.guesses = guesses;
            Form3.Show();
            this.Hide();
        }

        private void optionsButton_Click(object sender, EventArgs e)
        {
            Form2.Show();
            this.Hide();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }

Form2:

public partial class Form2 : Form
{
    Form1 Form1 = new Form1();

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Woord toevoeg query
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        //Form1.difficulty = comboBox1.Text;
        //Form1.guesses = comboBox2.Text;
        this.Close();
    }
}

Is there anything wrong with this?

Thanks in advance.


Solution

  • As said before, circular initialization is causing your exception.

    One way of solving it is to make Form2 accept Form1 as constructor parameter.

    Form1 form;
    
    public Form2(Form1 form1)
    {
        form = form1;
        InitializeComponent();
    }