Skip to content

Gendarme.Rules.Exceptions.UseObjectDisposedExceptionRule(git)

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

UseObjectDisposedExceptionRule

Assembly: Gendarme.Rules.Exceptions
Version: git

Description

It's usually a very bad idea to attempt to use an object after it has been disposed. Doing so may lead to crashes in native code or any number of other problems. In order to prevent this, and to report the problem in a clear way, classes should throw System.ObjectDisposedException from public methods if the object has been disposed. Note that there are some methods which should not throw ObjectDisposedException. This includes constructors, finalizers, Equals, GetHashCode, ToString, and Dispose.

Examples

Bad example:

internal sealed class WriteStuff : IDisposable
{
    public WriteStuff (TextWriter writer)
    {
        this.writer = writer;
    }
    // Objects are generally not in a useable state after being disposed so
    // their public methods should throw ObjectDisposedException.
    public void Write (string message)
    {
        writer.Write (message);
    }
    public void Dispose ()
    {
        if (!disposed) {
            writer.Dispose ();
            disposed = true;
        }
    }
    private bool disposed;
    private TextWriter writer;
}

Good example:

internal sealed class WriteStuff : IDisposable
{
    public WriteStuff (TextWriter writer)
    {
        this.writer = writer;
    }
    // In general all public methods should throw ObjectDisposedException
    // if Dispose has been called.
    public void Write (string message)
    {
        if (disposed) {
            throw new ObjectDisposedException (GetType ().Name);
        }
        writer.Write (message);
    }
    public void Dispose ()
    {
        if (!disposed) {
            writer.Dispose ();
            disposed = true;
        }
    }
    private bool disposed;
    private TextWriter writer;
}

Notes

  • This rule is available since Gendarme 2.6

Source code

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

Clone this wiki locally