Search code examples
c#wpfopenfiledialog

Is it good idea to define OpenFileDialog as a static class?


I have application with OpenFileDialog and i don't want OpenFileDialog new instance each time the user wants to add files (with Winforms this could be done inside the designer). So is it good idea to define OpenFileDialog as a Static class or perhaps Singleton

Edit

public static class OpenFileDialogCreation
{
    public static OpenFileDialog openFileDialog;

    public static void CreateDialog()
    {
        openFileDialog = new OpenFileDialog();
        openFileDialog.Title = "Select File(s)";
        openFileDialog.Filter = "*.doc|*.doc";         
        openFileDialog.Multiselect = true;
    } 
}

Solution

  • OpenFileDialog is a small class. A tiny .NET wrapper class around the unmanaged Windows api. The heavy stuff only happens when you call ShowDialog() and disappears when you close the dialog. The Winforms version of it is disposable (the WPF version isn't), but only because it inherits Dispose() from Component. It doesn't do anything.

    The only notable memory usage is a string[] that stores the selected files, the backing store for the FileNames property. Usually just one and you'd only use FileName, technically it can be thousands. Having it exceed a megabyte is very rare.

    So a static isn't a grave problem. Or desirable. Don't overlook the option of using a factory method:

    public static OpenFileDialog CreateDialog(string initialDir = null) {
        var dlg = new OpenFileDialog();
        dlg.Title = "Select Word documents";
        dlg.Filter = "Word documents (*.doc,*.docx)|*.doc;*.docx";
        dlg.DefaultExt = ".doc";
        dlg.Multiselect = true;
        if (initialDir != null) dlg.InitialDirectory = initialDir;
        return dlg;
    }