Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Overflow when trying to access form controls from class

Tags:

c#

I have a problem, after adding this code so I can access my MainWindow controls in 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
}

it now gives me "An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll" on line

this.mainControlPanel.ResumeLayout(false);

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

PS. Also, when I'm in Downloader class, should i access the controls like

textbox.Text

or

_controlsRef.textbox.Text

Both seem to give no compile errors, is there any difference between the two?

like image 419
Januszoff Avatar asked Sep 28 '22 10:09

Januszoff


1 Answers

Your Downloader class inherits MainWindow. When you instansiate it, according to the C# specification, the base class is initialized first. When MainWindow initializes, it creates a new instance of Downloader, which causes it eventually to stackoverflow, because you're in an endless cyclic dependency.

Since Downloader inherits MainWindow, there is no point in getting an instance of it via your constructor. You can simply access it's protected and public members from your derived.

For example:

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);
    }
}
like image 192
Yuval Itzchakov Avatar answered Oct 07 '22 20:10

Yuval Itzchakov