Skip to content

Gendarme.Rules.Correctness.EnsureLocalDisposalRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

EnsureLocalDisposalRule

Assembly: Gendarme.Rules.Correctness
Version: git

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

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally