IDISP016

November 25, 2021 ยท View on GitHub

Don't use disposed instance

TopicValue
IdIDISP016
SeverityWarning
EnabledTrue
CategoryIDisposableAnalyzers.Correctness
CodeDisposeCallAnalyzer

Description

Don't use disposed instance.

Motivation

Touching a disposed instance is often a bug as it should throw ObjectDisposedException.

namespace N
{
    using System.IO;

    public sealed class Foo
    {
        public void Bar()
        {
            var stream = File.OpenRead(string.Empty);
            stream.Dispose();
            var b = stream.ReadByte();
        }
    }
}

How to fix violations

Dispose after last usage.

Configure severity

Via ruleset file.

Configure the severity per project, for more info see MSDN.

Via #pragma directive.

#pragma warning disable IDISP016 // Don't use disposed instance
Code violating the rule here
#pragma warning restore IDISP016 // Don't use disposed instance

Or put this at the top of the file to disable all instances.

#pragma warning disable IDISP016 // Don't use disposed instance

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("IDisposableAnalyzers.Correctness", 
    "IDISP016:Don't use disposed instance", 
    Justification = "Reason...")]