How to Avoid the CA2000 Error from Code Analysis

by Larry Spencer Friday, June 17, 2011 4:05 PM

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;
}

Tags: ,

All | General

Comments (1) -

8/31/2011 10:55:42 AM #

very helpful, thanks a bunch!

Peter Austria

Add comment

About the Author

Larry Spencer

Larry Spencer develops software with the Microsoft .NET Framework for ScerIS, a document-management company in Sudbury, MA.