Skip to content

Gendarme.Rules.Correctness.EnsureLocalDisposalRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

EnsureLocalDisposalRule

Assembly: Gendarme.Rules.Correctness
Version: 2.10

Description

This rule checks that disposable locals are always disposed of before the method returns. Use a 'using' statement (or a try/finally block) to guarantee local disposal even in the event an unhandled exception occurs.

Examples

Bad example (non-guaranteed disposal):

void DecodeFile (string file)
{
    var stream = new StreamReader (file);
    DecodeHeader (stream);
    if (!DecodedHeader.HasContent) {
        return;
    }
    DecodeContent (stream);
    stream.Dispose ();
}

Good example (non-guaranteed disposal):

void DecodeFile (string file)
{
    using (var stream = new StreamReader (file)) {
        DecodeHeader (stream);
        if (!DecodedHeader.HasContent) {
            return;
        }
        DecodeContent (stream);
    }
}

Bad example (not disposed of / not locally disposed of):

void DecodeFile (string file)
{
    var stream = new StreamReader (file);
    Decode (stream);
}
void Decode (Stream stream)
{
    /*code to decode the stream*/
    stream.Dispose ();
}

Good example (not disposed of / not locally disposed of):

void DecodeFile (string file)
{
    using (var stream = new StreamReader (file)) {
        Decode (stream);
    }
}
void Decode (Stream stream)
{
    /*code to decode the stream*/
}

Notes

  • This rule is available since Gendarme 2.4
Clone this wiki locally