I have a method, which has a try/catch/finaly
block inside. Within the try block, I declare SqlDataReader
as follows:
SqlDataReader aReader = null;
aReader = aCommand.ExecuteReader();
In the finally
block, the objects which are manually disposed of are those which are set at the class level. So objects in the method which implement IDisposable
, such as SqlDataReader
above, do they get automatically disposed of? Close()
is called on aReader
after a while loop executes to get the contents of the reader (which should be Dispose()
as that calls Close()
). If there is no call to Close()
, would this object be closed/disposed of automatically when the method finishes or the object goes out of scope?
EDIT: I am aware of the using
statement but there are scenarios which are confusing me.
No, objects are not automatically disposed when they go out of scope.
They're not even guaranteed to be disposed if/when they're garbage-collected, although many IDisposable
objects implement a "fallback" finaliser to help ensure that they're eventually disposed.
You are resposible for ensuring that any IDisposable
objects are disposed, preferably by wrapping them in a using
block.
You should use a using {...}
block to wrap your IDisposable objects in - the Dispose()
method (which for SqlDataReader passes off to the Close()
method) will be called when the using block ends. If you do not use using
, the object will not be automatically disposed when it goes out of scope - it will be up to the object finalizer, if it has one, to get rid of resources when it is garbage collected
using (SqlDataReader aReader = aCommand.ExecuteReader())
{
// ... do stuff
} // aReader.Dispose() called here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With