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.

1

There are 1 answers

0
BJ Myers On BEST ANSWER

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 the Dispose() method of the parent form.

private FormCustomerList frm;
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
    frm = new FormCustomerList();
    frm.MdiParent = this;
    frm.Show();
}

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.

private List<FormCustomerList> frms = new List<FormCustomerList>();
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
    FormCustomerList frm = new FormCustomerList();
    frms.Add(frm);
    frm.MdiParent = this;
    frm.Show();
}