wow
wow

Reputation: 3899

StackOverflow when calling form from class

I am getting a StackOverflowException when I am calling my form from my class.

In my MainForm I call the Youtube.cs class using this, Youtube yt = new Youtube();. Then in my Youtube class I call the MainForm using, MainForm main = new MainForm();. I believe this is what is causing the StackOverflow as it seems to be creating a loop.

I need to access the Youtube class from MainForm and also MainForm from my Youtube class so is there any way around this without causing the StackOverflow?

This is the from the top of MainForm:

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    Youtube yt = new Youtube();

And this is from the top of Youtube.cs:

class Youtube
{
    MainForm main = new MainForm();

Upvotes: 2

Views: 1679

Answers (3)

Wouter de Kort
Wouter de Kort

Reputation: 39898

You need to pass your MainForm to your YouTube class as a parameter.

public class MainForm
{
   private Youtube youtube;
   public MainForm()
   {
       youtube = new Youtube(this);
   }
}

And then in you Youtube class store this reference:

public class Youtube
{
   private MainForm form;

   public Youtube(MainForm form)
   {
       this.form = form;
   }
}

Upvotes: 3

sloth
sloth

Reputation: 101042

Yes, this is causing the StackOverFlowException.

One way is to pass the Form into your Youtube class via the constructor.


Example:

in the MainForm class:

Youtube yt = new Youtube(this)

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        yt = new Youtube(this);
    }

    Youtube yt = null;

in the Youtube class:

public Youtube(MainForm mainform)
{
    // do something with mainform
}

Upvotes: 3

Adil
Adil

Reputation: 148110

Pass form object to YouTube class, and use the object in YouTube class.

public class Youtube
{
     MainForm m_MainForm = null;
     public Youtube(MainForm frm)
     {
            m_MainForm = frm;
     }

}  

Upvotes: 7

Related Questions