Stack overflow when trying to access form controls from a class

I had a problem after adding this code, so I can access the MainWindow elements in the Downloader class:

public partial class MainWindow : Form { private Downloader fileDownloader; public MainWindow() { InitializeComponent(); fileDownloader = new Downloader(this); } //smth } 

and

 class Downloader : MainWindow { private MainWindow _controlsRef; public Downloader(MainWindow _controlsRef) { this._controlsRef = _controlsRef; } // smth } 

now it gives me a "Unhandled exception like" System.StackOverflowException "occurred in System.Windows.Forms.dll" in the line

 this.mainControlPanel.ResumeLayout(false); 

in MainWindow.Designer.cs. If I comment on the code above, it works fine. Any ideas please?

PS. Also, when I am in the Downloader class, I have to access controls like

 textbox.Text 

or

 _controlsRef.textbox.Text 

Both don't seem to compile errors, is there any difference between the two?

+5
source share
2 answers

Your Downloader class inherits from MainWindow . When you initialize it, according to the C # specification, initialization of the base class begins first. When MainWindow initialized, it creates a new instance of Downloader , which ultimately causes it to happen on stackoverflow, because you are in an infinite loop dependency.

Since Downloader inherits from MainWindow , it makes no sense to get an instance of it through your constructor. You can simply access protected and public from your derivative.

For instance:

 public partial class MainWindow : Form { protected string Bar { get; set; } public MainWindow() { Bar = "bar"; InitializeComponent(); } } public class Downloader : MainWindow { public void Foo() { // Access bar: Console.WriteLine(Bar); } } 
+3
source

This is a problem because here you have a circular dependency, that is, both methods are waiting for each other to complete.

verify

 public MainWindow() { InitializeComponent(); fileDownloader = new Downloader(this);//this wait to complete downloader intialization } public Downloader(MainWindow _controlsRef)//this wait to complete mainwindow first { this._controlsRef = _controlsRef; } 

my point is to say, since you inherit the Downloader from MainWindow, which in the crating downloader instace constructor ... and the loader first calls the Mainwindow constructor as its parent box, for you here Solution

if you want a link you can do it

 public partial class MainWindow : Form { protected MainWindow mainWindow; public MainWindow() { InitializeComponent(); mainWindow = this; } //smth } class Downloader : MainWindow { public Downloader() { //this.mainWindow //will give you reference to main winsow } // smth } 
+1
source

All Articles