And using statement is always better, because ...
- you cannot forget to call
Dispose() , even if the code develops in different code paths Dispose() is called even if there is an exception. It also checks for null before calling Dispose() , which can be useful (if you are not just calling new ).
One non-obvious (for me, anyway) trick with using is how you can avoid over-nesting when you have multiple disposable objects:
using (var input = new InputFile(inputName)) using (var output = new OutputFile(outputName)) { input.copyTo(output); }
The VS code formatter will leave two statements starting in the same column.
In fact, in some situations, you donβt even need to repeat the using ... statement
using (InputFile input1 = new InputFile(inputName1), input2 = new InputFile(inputName2))
However, restrictions apply here to declare multiple variables on the same line, so the types must be the same, and you cannot use the implicit var type.
Trevor robinson
source share