1

I am getting the error An unhandled exception of type 'System.StackOverflowException' occurred in Forte Sender.exe in my code. I have the understanding that this means there is an infinite loop in my code, but I cannot seem to find this loop. Here is my code:

Form1:

public partial class MainBox : Form
{
    //Making a name for the ApplicationProperties form. It can be opened when called.
    ApplicationProperties ApplicationPropertiesWindow = new ApplicationProperties();
    //All of the functions for form1 below.

Form2:

public partial class ApplicationProperties : Form
{
    MainBox MainBoxWindow = new MainBox();
    //All of the funcitons for form2 below.

So I have noticed that if I take out the MainBox MainBoxWindow = new MainBox(); that the program will run correctly. But I need that instance there to call a function in Form1. How can I get around this problem? Either a different way to call the function or to solve the infinite loop.

4 Answers 4

6

Well, your MainBox creates an ApplicationProperties, which in turn creates a MainBox, which creates an ApplicationProperties, and so on ad infinitum. Obviously you need to break up this cycle.

As your code stands right now you would probably want to remove the new MainBox() for the properties form and inject it afterwards, for example:

ApplicationProperties ApplicationPropertiesWindow = new ApplicationProperties();
ApplicationPropertiesWindow.MainBoxWindow = this;

And

public partial class ApplicationProperties : Form
{
    public MainBox MainBoxWindow { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very well explained answer, thank you. This worked out great for me.
2

You just open one form and it opens another from it's constructor and it opens the first one again in t's contructor and so on...

Fields initializers executed right before constructor when an instance is created.

Comments

2

Your ApplicationProperties class creates a MainBox object, and your MainBox object creates an ApplicationProperties object. This is the loop. Each call to new is another constructor call in that loop. The constructors call each other in term in something called mutual recursion, which leads to your stack overflow.

Comments

2

You're Creating MainBox Inside ApplicationProperties and ApplicationProperties inside MainBox this will keep on creating Instances resulting StackOverFlowException

To avoid this you could create Instances in OnLoad overridden method, but creating Instances mutually tied doesn't make sense did you mean to use the same reference?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.