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?
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();
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With