I have a basic form that will attempt to load and play a video of the user. The form can be called from a public static ShowDialogForm method. That method will attempt to initialize a video if successful then the form is returned otherwise the action is canceled. At my office we use a refactoring tool, and it is complaining about the lack of a using statement in my method. So my question is benifit, if any does the using statement offer in this instance.
This is the original code
public static DialogResult ShowDialogForm(VideoNames videoName, Course course, IWin32Window parent)
{
FlashPlayer form = new FlashPlayer();
if (form.Initialize(videoName, course))
{
return form.ShowDialog(parent);
}
else
{
return DialogResult.Cancel;
}
}
This is the code suggested by the refactoring tool
public static DialogResult ShowDialogForm(VideoNames videoName, Course course, IWin32Window parent)
{
using (FlashPlayer form = new FlashPlayer())
{
if (form.Initialize(videoName, course))
{
return form.ShowDialog(parent);
}
else
{
return DialogResult.Cancel;
}
}
}
Well, the tool’s complaint is valid. When you display a form with ShowDialog() then the form object doesn’t automatically get disposed like it does when you use Show(). This is important, you normally use a dialog to let the user enter values that you then retrieve after ShowDialog returns. Having the form controls disposed makes that risky, likely to trigger an ObjectDisposedException.
So you always wrap the dialog creation, display and result retrieval with a using statement so the form gets disposed after everything is done.
Note however that you don’t actually use this dialog to retrieve anything. Which probably means it shouldn’t be a dialog at all. So use Show() and you don’t have to dispose it. And the user gets the freedom to continue using the rest of your user interface, assuming that’s appropriate. Non-modal user interfaces are always preferred.