5
Reply

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

Murali Poola

Murali Poola

12y
7.1k
0
Reply

    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()

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

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

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

    I prefer the "using" statement over manual Dispose.