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

PREVIEWING: may/unit-testing