Search code examples
c#winformsstack-overflow

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();

Solution

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