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

csharpdev picture csharpdev · Dec 2, 2009 · Viewed 14.5k times · Source

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.

Answer

LukeH picture LukeH · Dec 2, 2009

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.