Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Dispose() vs when an object goes out scope/method finishes

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.

like image 719
csharpdev Avatar asked Dec 02 '09 13:12

csharpdev


2 Answers

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.

like image 99
LukeH Avatar answered Oct 01 '22 18:10

LukeH


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
like image 23
thecoop Avatar answered Oct 01 '22 18:10

thecoop