Why is this an issue?
Typically you want to use using
to create a local IDisposable
variable; it will trigger disposal of the object when
control passes out of the block’s scope. The exception to this rule is when your method returns that IDisposable
. In that case
using
disposes of the object before the caller can make use of it, likely causing exceptions at runtime. So you should either remove
using
or avoid returning the IDisposable
.
Noncompliant code example
public FileStream WriteToFile(string path, string text)
{
using (var fs = File.Create(path)) // Noncompliant
{
var bytes = Encoding.UTF8.GetBytes(text);
fs.Write(bytes, 0, bytes.Length);
return fs;
}
}
Compliant solution
public FileStream WriteToFile(string path, string text)
{
var fs = File.Create(path);
var bytes = Encoding.UTF8.GetBytes(text);
fs.Write(bytes, 0, bytes.Length);
return fs;
}