tags:

views:

71

answers:

3

I'm creating a windows app in c# 2008 that will have around 8-10 dialog boxes. I want these forms to exist throughout the life of the program. Where's the best place to create and store the objects?

I'm coming from Delphi, where Form objects were usually stored in global variables.

I'm tempted to do it in the static Program class. Should I put them in the main form instead?

Thanks for helping a C# newb out.

+4  A: 

Why do you want these dialog boxes to exist throughout the life of the program? In general, dialog boxes are created when they're needed, get used, then are destroyed. If you need to display it again, you create a new one and use it.

If you have a legitimate reason to keep them around, then that's fine, but don't use the Program class for this. I'm assuming that your application has a main form that all others get launched from. If this is the case, make them instance variables on that form and use them from there.

Adam Robinson
A: 

In generaly, there is no reason to store the dialogs for reusing. The typical scenario is:

using( MyDialog dlg = new MyDialog() ) {
    dlg.MyTextProperty = "Are you realy sure, you want do XY operation?";
    dlg.MyNumberProperty = 15;

    DialogResult rslt = dlg.ShowDialog( this ); // the "this" is current form or control
    if ( rslt == DialogResult.OK ) {
        object userInput = dlg.UserInput;
        // do what you want with user input
    }
}
TcKs
+1  A: 

Forms are expensive objects, they have a lot of internal state. Caching makes sense if creating the data is expensive. Forms behave the exact opposite, creating their data is cheap. Using cached data becomes expensive when Windows has swapped out the data to the paging file. Which is very likely to happen in your case, the dialogs wouldn't be used very frequently. It actually takes longer to show the dialog.

If your data to fill the dialog is expensive to create then cache that data, not the form.

Hans Passant