Suppose I have the following:
using(var ctx = DataContextFactory.Create(0))
{ ... Some code ... }
Why not just do the following and lose a
A using statement is always better because...
Dispose(), even as the code evolves into different code pathsDispose() gets called even if there's an exception. It also checks for null before calling Dispose(), which may be useful (assuming you're not just calling new).One non-obvious (to me, anyway) trick with using is how you can avoid excessive 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 the two statements starting in the same column.
In fact, in some situations you don't even have to repeat the using statement...
using (InputFile input1 = new InputFile(inputName1), input2 = new InputFile(inputName2))
However, the restrictions for declaring multiple variables on the same line applies here so the types must be the same and you cannot use the implicit type var.