IDISP002

November 25, 2021 ยท View on GitHub

Dispose member

TopicValue
IdIDISP002
SeverityWarning
EnabledTrue
CategoryIDisposableAnalyzers.Correctness
CodeFieldAndPropertyDeclarationAnalyzer

Description

Dispose the member as it is assigned with a created IDisposable.

Motivation

In the example below the file will be left open.

public class Foo
{
    private FileStream stream = File.OpenRead("file.txt");
}

How to fix violations

Implement IDisposable and dispose the member.

public sealed class Foo : IDisposable
{
    private FileStream stream = File.OpenRead("file.txt");

    public void Dispose()
    {
        this.stream.Dispose();
    }
}

Configure severity

Via ruleset file.

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

Via #pragma directive.

#pragma warning disable IDISP002 // Dispose member
Code violating the rule here
#pragma warning restore IDISP002 // Dispose member

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

#pragma warning disable IDISP002 // Dispose member

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("IDisposableAnalyzers.Correctness", 
    "IDISP002:Dispose member", 
    Justification = "Reason...")]