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.
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:
FileStream
)DbConnection
)TransactionScope
/ DbTransaction
)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.