Prevents the return of an IDisposable from a using statement

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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