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 (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?
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(); } }
} 3 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.