2

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();
1
  • 1
    can you show some code? We need to see how each class "Accesses" the other Commented Aug 3, 2012 at 14:08

3 Answers 3

7

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;
     }

}  
Sign up to request clarification or add additional context in comments.

Comments

3

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
}

Comments

3

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;
   }
}

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.