Do You Know What Happens When We Use "Using?"

When we write inside the using block the compiler coverts the code as try and finally block. This is the reason we don’t need to explicitly release or dispose the object, once it’s being used, as the object created gets disposed inside the finally block.

Please see the code snippet given below as well as the respective IL code for better understanding.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace ConsoleApplication1 {  
  7.     public class Program {  
  8.         static void Main(string[] args) {  
  9.             using(var obj = new CustomDbConnection()) {  
  10.                 //Your Code Goes Here  
  11.             }  
  12.         }  
  13.     }  
  14. }  

Respective IL code

In the code given below, you can see the code given above within using interpreted as try, finally block and the dispose method gets called inside the finally.

Note

Within using, you can instantiate the objects of class, which implements IDisposable interface, so dispose method can be called.

  1. .method private hidebysig static void Main(string[] args) cil managed {.entrypoint  
  2.         // Code size 29 (0x1d)  
  3.         .maxstack 2.locals init([0] class ConsoleApplication1.CustomDbConnection obj, [1] bool CS$4$0000)  
  4.     IL_0000: nop  
  5.     IL_0001: newobj instance void ConsoleApplication1.CustomDbConnection::.ctor()  
  6.     IL_0006: stloc .0.try {  
  7.         IL_0007: nop  
  8.         IL_0008: nop  
  9.         IL_0009: leave.s IL_001b  
  10.     } // end .try  
  11.     finally {  
  12.         IL_000b: ldloc .0  
  13.         IL_000c: ldnull  
  14.         IL_000d: ceq  
  15.         IL_000f: stloc .1  
  16.         IL_0010: ldloc .1  
  17.         IL_0011: brtrue.s IL_001a  
  18.         IL_0013: ldloc .0  
  19.         IL_0014: callvirt instance void[mscorlib] System.IDisposable::Dispose()  
  20.         IL_0019: nop  
  21.         IL_001a: endfinally  
  22.     } // end handler  
  23.     IL_001b: nop  
  24.     IL_001c: ret  
  25. // end of method Program::Main  

 

I believe, this helps us to understand what actually happens when we write the code inside the using block.