Skip to content

Latest commit

 

History

History
83 lines (66 loc) · 1.75 KB

IDISP017.md

File metadata and controls

83 lines (66 loc) · 1.75 KB

IDISP017

Prefer using

Topic Value
Id IDISP017
Severity Warning
Enabled True
Category IDisposableAnalyzers.Correctness
Code DisposeCallAnalyzer

Description

Prefer using.

Motivation

namespace N
{
    using System.IO;

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

Prefer using in the code above. It is cleaner than adding try-finally. The code above will not dispose the file if the read fails.

How to fix violations

namespace N
{
    using System.IO;

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

Configure severity

Via ruleset file.

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

Via #pragma directive.

#pragma warning disable IDISP017 // Prefer using
Code violating the rule here
#pragma warning restore IDISP017 // Prefer using

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

#pragma warning disable IDISP017 // Prefer using

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("IDisposableAnalyzers.Correctness", 
    "IDISP017:Prefer using", 
    Justification = "Reason...")]