Missed ‘using’ opportunity¶
ID: cs/missed-using-statementKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - quality - maintainability - readability - language-featuresQuery suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
It is good practice (and often essential for correctness) to dispose of resources (for example file handles, graphics handles or database connections) when a program no longer needs them. For resources that are used only within a single method, a common idiom is to enclose the code that uses the resource in atry block and dispose of the resource in thetry’sfinally block. This idiom is in fact so common that C# provides a shorter, tidier syntax for it in the form of theusing statement.
Recommendation¶
Given the explicit language support provided in this case, it is more idiomatic to use theusing statement in preference to thetry-finally technique; it also helps to clearly communicate the intent of your code to other programmers.
Example¶
In this example atry block is used to ensure resources are disposed of even if the program throws an exception.
classMissedUsingOpportunity{staticvoidMain(string[]args){StreamReaderreader=null;try{reader=File.OpenText("input.txt");// ...}finally{if(reader!=null){((IDisposable)reader).Dispose();}}}}
The example can be significantly simplified by making use of theusing block instead.
classMissedUsingOpportunityFix{staticvoidMain(string[]args){using(StreamReaderreader=File.OpenText("input.txt")){// ...}}}
References¶
MSDN:using Statement.
J. Albahari and B. Albahari,C# 4.0 in a Nutshell - The Definitive Reference, p. 138.