Missing Dispose call on local IDisposable¶
ID: cs/local-not-disposedKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - correctness - efficiency - external/cwe/cwe-404 - external/cwe/cwe-459 - external/cwe/cwe-460Query suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Objects whose type implementsIDisposable should be disposed of by callingDispose.
Recommendation¶
If possible, wrap the allocation of the object in ausing block to automatically dispose of the object once theusing block has completed.
If this is not possible, ensure thatDispose is called on the object. It is usually recommended to callDispose within afinally block, to ensure that the object is disposed of even if an exception is thrown.
Example¶
In this example, aFileStream is created, but it is not disposed of.
usingSystem;usingSystem.IO;classBad{longGetLength(stringfile){varstream=newFileStream(file,FileMode.Open);returnstream.Length;}}
In the revised example, ausing statement is used to ensure that the file stream is properly closed.
usingSystem;usingSystem.IO;classGood{longGetLength(stringfile){using(varstream=newFileStream(file,FileMode.Open))returnstream.Length;}}
References¶
MSDN:IDisposable Interface.
Common Weakness Enumeration:CWE-404.
Common Weakness Enumeration:CWE-459.
Common Weakness Enumeration:CWE-460.