Question: I'm writing a WindowsForms application in MS Visual C#, and I need two forms to be able to reference each other. As I test, I created two buttons on Form1 -- one button that displays Form2 and another button that hides it (code is below).

I want to do the same thing for Form2 -- create two buttons that hide or show Form1. I used the same method that I used for Form1, but when I compile the application, it seems to get caught in an infinite loop and I get a StackOverflow message.

How can I change the code so that both forms are able to reference each other?

Form1 code:

```
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    Form2 frm2;
    public Form1()
    {
        InitializeComponent();
        frm2 = new Form2();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frm2.Visible = false;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        frm2.Visible = true;
    }
}
}

```

Form2 code:

```
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
    Form1 frm1;
    public Form2()
    {
        InitializeComponent();
        frm1 = new Form1();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frm1.Visible = false;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        frm1.Visible = true;
    }
}
}

```

Answer: 
The "Other form" needs to be given to the appropriate instance. Something like this should help.

```
public partial class TogglingForm : Form
{
    TogglingForm Other {get; set;}
    public TogglingForm()
    {
        InitializeComponent();
    }        

    private void HideOther_Click(object sender, EventArgs e)
    {
        Other.Visible = false;
    }

    private void ShowOther_Click(object sender, EventArgs e)
    {
        Other.Visible = true;
    }
}

....

static void Main()
{
   var first = new TogglingForm();
   var second = new TogglingForm {Other = first};
   first.Other = second;

   first.Show();
}   

```
When you create an instance of Form2 on the frm1 object, this new instance creates another Form1 instance, that creates a new Form 2 instance, that...

Do you see the infinite loop?

Create one instance of each other on the main class or as global application variables. Or pass them as parameter to each other. The .NET framework will just reference them without alocating new memory space.