Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call System.IDisposable.Dispose on object 'emailForm' before all references to it are out of scope

Tags:

c#

.net

winforms

I have the following function:

    private void emailVideoButton_Click(object sender, EventArgs e)
    {
        VideoEMailForm emailForm = new VideoEMailForm();
        emailForm.ShowDialog();
    }

Which gives me the following warning:

Warning 1 CA2000 : Microsoft.Reliability : In method 'VideoPlayerControl.emailVideoButton_Click(object, EventArgs)', call System.IDisposable.Dispose on object 'emailForm' before all references to it are out of scope.

I read this link http://msdn.microsoft.com/en-us/library/ms182289(v=vs.80).aspx and gathered that I needed to call .Dispose like so:

    private void emailVideoButton_Click(object sender, EventArgs e)
    {
        VideoEMailForm emailForm = new VideoEMailForm();
        emailForm.ShowDialog();
        emailForm.Dispose();
    }

But then I get the following warning:

Warning 1 CA2000 : Microsoft.Reliability : In method 'VideoPlayerControl.emailVideoButton_Click(object, EventArgs)', object 'emailForm' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'emailForm' before all references to it are out of scope.

Can anyone help me to get rid of this warning?

like image 661
Harry Boy Avatar asked Jun 04 '13 14:06

Harry Boy


2 Answers

What the compiler is trying to say is that if an exception is thrown in emailForm.ShowDialog(), Dispose() will not get called.

Use a using statement to ensure that it will get called either way.

private void emailVideoButton_Click(object sender, EventArgs e)
{
    using (VideoEMailForm emailForm = new VideoEMailForm())
    {
        emailForm.ShowDialog();
    }
}

This is equivalent to this code:

private void emailVideoButton_Click(object sender, EventArgs e)
{
    VideoEMailForm emailForm = null;
    try
    {
        emailForm = new VideoEMailForm();
        emailForm.ShowDialog();
    }
    finally
    {
        if (emailForm != null) 
        {
            ((IDisposable)emailForm).Dispose();
        }
    }
}
like image 163
Rotem Avatar answered Oct 15 '22 23:10

Rotem


You need the using statement, which will call Dispose() in a finally block to make sure it gets disposed even if an exception is thrown.

like image 22
SLaks Avatar answered Oct 15 '22 23:10

SLaks