Which is better, and when: using an operator or calling Dispose () on an IDisposable in C #?

Suppose I have the following:

using(var ctx = DataContextFactory.Create(0)) { ... Some code ... } 

Why not just do the following and lose a pair of braces ?:

 var ctx = DataContextFactory.Create(0); ctx.Dispose(); 

Thanks for the advice!

+6
c # idisposable using-statement
source share
5 answers

The first is better. It ensures that it will be deleted even if an exception is thrown, and it correctly handles the case where Create(0) returns null (i.e., it does not try to call Dispose() on the null instance).

+26
source share

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.

+7
source share

Where you can, use using for the reasons stated by Mark. OTOH is not a dead decision, because sometimes the lifetime of an object cannot be defined as a lexical scale, so use it wisely.

+3
source share

The only place where you do not want to use the used block is the place where the one-time object is outside the function. In this case, your class should implement IDisposable and destroy the object in its Dispose ().

+3
source share

The using statement gives good syntax plus exception protection. You cannot leave the using statement without calling Dispose (it translates into a finally block with a call for disposal). In the second scenario, if you have an exception between Create and Dispose, you will not call dispose directly. This is not a problem if you use unmanaged resources, but if so, you will miss.

+2
source share

All Articles