IDISP015

November 25, 2021 ยท View on GitHub

Member should not return created and cached instance

TopicValue
IdIDISP015
SeverityWarning
EnabledTrue
CategoryIDisposableAnalyzers.Correctness
CodeMethodReturnValuesAnalyzer

Description

Member should not return created and cached instance.

Motivation

When calling the method below it is not obvious if we are responsible for disposing the returned instance. Avoid mixing created and cached disposables.

public IDisposable Bar()
{
    if (condition)
    {
        return this.disposable;
    }

    return File.OpenRead(string.Empty);
}

How to fix violations

Redesign.

Configure severity

Via ruleset file.

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

Via #pragma directive.

#pragma warning disable IDISP015 // Member should not return created and cached instance
Code violating the rule here
#pragma warning restore IDISP015 // Member should not return created and cached instance

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

#pragma warning disable IDISP015 // Member should not return created and cached instance

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("IDisposableAnalyzers.Correctness", 
    "IDISP015:Member should not return created and cached instance", 
    Justification = "Reason...")]