Reputation: 1155
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.
Upvotes: 1
Views: 3018
Reputation: 73442
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?
Upvotes: 2
Reputation: 209465
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.
Upvotes: 2
Reputation: 1325
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.
Upvotes: 2
Reputation: 437336
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; }
}
Upvotes: 6