Prevents the return of an IDisposable from a using statement

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: csharp-best-practices/using-idisposable-return

Language: C#

Severity: Error

Category: Best Practices

Description

In a using statement, the acquired IDisposable instance is disposed of when control leaves the block. If this instance is returned from a function, a runtime error will likely occur when the value is read.

Non-Compliant Code Examples

using System.IO;
using System.Text;

class NonCompliant {
    public FileStream Write(string filePath)
    {
        using (FileStream fs = new FileStream(filePath, FileMode.Create))
        {
            var bytes = Encoding.UTF8.GetBytes("foo");
            fs.Write(bytes, 0, bytes.Length);
            return fs;
        }
    }
}

Compliant Code Examples

using System.IO;
using System.Text;

class Compliant {
    public FileStream Write(string filePath)
    {
        FileStream fs = new FileStream(filePath, FileMode.Create);
        var bytes = Encoding.UTF8.GetBytes("foo");
        fs.Write(bytes, 0, bytes.Length);
        return fs;
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis