Prevents the return of an IDisposable from a using statement
TRY THIS RULE 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 ;
}
}
Seamless integrations. Try Datadog Code Analysis