CA2000 Dispose objects before losing scope
In method FormMain.barButtonItem1_ItemClick(object, ItemClickEventArgs)
Call System.IDisposable.Dispose on object 'frm' before all references to it are out of scope. Winpro FormMain.cs 32
Method :
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
FormCustomerList frm = new FormCustomerList();
frm.MdiParent = this;
frm.Show();
}
This is not a serious problem, but why is this fired?
I can't use finally frm.Dispose()
or using()
because form will not be shown.
I have also tried to handle form closing and then dispose but violation is always here.
Code Analysis can't tell that
frm
is still doing anything after it exits scope. In this specific case, the object needs to stay alive after the function is done with it.The "correct" way to handle this is to maintain a reference to
frm
in the parent form. This reference can then be disposed in theDispose()
method of the parent form.If you have multiple sub forms that can be created (which is likely if you're using MDI), you can maintain a
List<>
of child forms.