Search code examples
c#garbage-collectiondisposeusing

Do I have to use a “using” statement in a short method?


Do I have to use a using statement to dispose immediately even in a method? Or will the ending of the method cause an automatic Dispose of all local variables including graphics? (I’m asking this because I’ve seen examples that have Dispose calls at the end of methods, and wanted to know if that’s really necessary.)

Thanks.


Solution

  • Yes, you do. Going out of scope does not do anything; it does not call Dispose(), it does not garbage-collect, it does not call a finalizer.

    If the type is IDisposable, then yes. It is your job to tidy up after yourself (assuming that the object is actually "done with" at this point).

    Possible side-effects of not doing this:

    • files get left open and cause access-exceptions (FileStream)
    • connections get left open and cause pool saturation (DbConnection)
    • unmanaged handles get saturated and cause resource starvation (any winforms/etc)
    • transactions get left open and cause blocking (TransactionScope / DbTransaction)
    • etc

    basically, bad things.

    Furthermore, in most cases where you see Dispose() at the bottom of the method, a using would be preferable. There are some cases where that isn't possible (fields on an object, for example), but the point remains: it sounds like those are bad examples.