Missing Dispose call on local IDisposable¶
ID: cs/local-not-disposed
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- efficiency
- maintainability
- external/cwe/cwe-404
- external/cwe/cwe-459
- external/cwe/cwe-460
Query suites:
- csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Objects whose type implements IDisposable
should be disposed of by calling Dispose
.
Recommendation¶
If possible, wrap the allocation of the object in a using
block to automatically dispose of the object once the using
block has completed.
If this is not possible, ensure that Dispose
is called on the object. It is usually recommended to call Dispose
within a finally
block, to ensure that the object is disposed of even if an exception is thrown.
Example¶
In this example, a FileStream
is created, but it is not disposed of.
using System;
using System.IO;
class Bad
{
long GetLength(string file)
{
var stream = new FileStream(file, FileMode.Open);
return stream.Length;
}
}
In the revised example, a using
statement is used to ensure that the file stream is properly closed.
using System;
using System.IO;
class Good
{
long GetLength(string file)
{
using (var stream = new FileStream(file, FileMode.Open))
return stream.Length;
}
}
References¶
MSDN: IDisposable Interface.
Common Weakness Enumeration: CWE-404.
Common Weakness Enumeration: CWE-459.
Common Weakness Enumeration: CWE-460.