Murali Poola
Which is better, and when: using statement or calling Dispose() on an IDisposable in C#?
By Murali Poola in .NET on Apr 23 2012
  • Murali Poola
    Apr, 2012 23

    A 'using' statement is always better becauseĀ 

    a) you can't forget to call Dispose, even as the code evolves into different code paths, andĀ 
    b) Dispose gets called even if there's an exception. It also checks for null before calling Dispose, which may be useful.

    The only place you don't want to use a using block is where the disposable object is scoped outside of the function. In this case, your class should implement IDisposable and dispose of the object in its Dispose()

    • 4
  • Mahesh Chand
    Jul, 2012 12

    I agree. I prefer the "using" statement over manual Dispose.

    • 1
  • Vishal Jadav
    Aug, 2016 15

    Using "using" statement because it will automatically call dispose when cursor moves out of that block at runtime.

    • 0
  • sanjib kotal
    Jul, 2016 9

    Using should be used whereever applicable. It will automatically dispose off once program is out of the block

    • 0
  • Sachin Kalia
    Apr, 2014 22

    I prefer the "using" statement over manual Dispose.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS