In my continuing quest to live a Good Life, I have been turning Code Analysis on for all my Visual Studio 2010 projects. Today, I thought the Universe was rewarding my good intentions with a spurrious error message. Then I found Enlightenment. I want to pass on to you the problem and the solution.
The following code provoke error CA2000 from Code Anaysis:
CA2000 : Microsoft.Reliability : In method 'CA2000.MakeStream1()', object 'strm' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'strm' before all references to it are out of scope.
static FileStream MakeStream1()
{
var strm = File.Create(@"test.txt");
strm.WriteByte(0);
return strm;
}
But wait! I promise that I'm going to Dispose() the Stream in the calling method! Does this mean that I can't return an IDisposable without drawing a CA2000 penalty?
No. The reason for the slap on the wrist is that the WriteByte call could throw an Exception, in which case the strm variable would be orphaned -- neither Disposed nor returned.
The solution is to demonstrate to Code Analysis that you will at least not orphan the Stream in the method being analyzed.
static FileStream MakeStream2()
{
var strm = File.Create(@"test.txt");
try
{
strm.WriteByte(0);
}
catch
{
// Code Analysis is now satisfied that
// we're Disposing our stream in the
// event of a problem.
strm.Dispose();
throw;
}
return strm;
}