What’s a good technique to create a WinForms Form instance, display it (non-modally) but not have to keep a reference around to it? Normally, as soon as the variable goes out of scope, the form is closed:
var form = new SuperDuperForm();
form.Show();
// Form has probably been closed instantly
I don’t want to have to keep track of instances of the form, I want it so that when the user closes the form, it is disposed. One idea I’ve had that I’m going to implement is a kind of controller that I use to open and display forms, that will keep track of them and monitor when they are closed via callbacks.
I’m just wondering if there are any neat tricks to get away without that. Any ideas?
You don’t have to do this at all – Winforms does it for you. When you show a form, it gets added to the Application.OpenForms, property, and when you close the form, it is automatically removed.
A Windows Form will never be eligible for garbage collection while it is open, and will also automatically be disposed when it is closed. Quoting from the Form.Close documentation:
In other words, for the general case when you "fire and forget", resource management is automatic.