How to avoid c# (winforms) creating pointers to forms?

In c# winforms, I am having a problem whereby this block of code will create two variables that point to the same form instead of two different instances of the form:

Form formA = new LoginForm();
Form formB = formA;
formB.Close();

When formB is closed, both forms are closed. I am trying to avoid this, however I cannot find any solution such as formB = new Form(formA);

In my real solution, there are extra controls added to the first form (formA), and some additional data stored in the fields of the form. This is why I need to duplicate the first form

Any help is much appreciated!

Jon Skeet
people
quotationmark

If you want two forms, create two forms - two independent objects - by calling the constructor twice:

Form formA = new LoginForm();
Form formB = new LoginForm();

Now they're independent objects. Note that there's nothing winforms specific about this - it's the same for all classes.

EDIT: If you want to create a clone of the original form, you still need to create a new object - and each of the controls within the form would need to be cloned as well (a control can't have two parents). Cloning is a tricky business to get into, and I'd try to avoid it here if possible. Instead, I would try to effectively replay the same original actions which added the controls or set the data in the original form.

You haven't said much about what information is within your form, but if it's complex data, you probably want to isolate that from the form, encapsulating it in its own class... then you can decide whether you want a deep or shallow clone of that object when you create the second form.

people

See more on this question at Stackoverflow