Search code examples
c#stack-overflow

Stack overflow error when trying to inicialize variable c#


Whenever i open the TradeForm menu, i get this error on the line that says Conditions con = new Conditions();

System.StackOverflowException

Here is the code that is relevant


public partial class TradeForm : Form
    {
        Conditions con = new Conditions();
        


        public TradeForm()
        {
            InitializeComponent(); 
            
        }

        
        public void button1_Click(object sender, EventArgs e)
        {
            if(con.foo >= 1)
            {
                lst1.Text = "text";
                res.Luxuries++;
                button1.Hide();
            }
      }

    }

and in another class named Properties

 public class Conditions : TradeForm
    {
        public int foo = 0;
    }

Solution

    1. As Conditions inherits from TradeForm, each time you create a new Conditions, you are creating a new TradeForm.

    2. Whenever you create a TradeForm you create a new Conditions object as per the line throwing the exception.

    3. When you create a new Conditions, you go back to 1.

    This loops infinitely, hence the StackOverflow exception.