Call .Dispose() Every Time we Can call it?

F

Frank Lund

Should we call .Dispose() every chance we get... on every object that
exposes .Dispose()... and every time we have such an object?

For example, is it true that *every* time I create a DataTable and use it,
that I should call .Dispose of the DataTable instance when I'm done with it?

I was told this is a good .NET programming practice. But I also thought that
..Dispose was there for us to use to clean up objects that actually need
cleaning up - like if we have an object that holds a file handle or database
connection... in that case we'd certainly implement Dispose and cut
connections etc in it. But what about DataTable and other "similar"
..NET-provided objects that apparently don't really hold references to files,
databases, and the like? Is there a good reason to call Dispose on those
objects anyway?

Thanks.
 
S

Scott M.

The simple response is that everything you said is 100% correct. You can't
go wrong by calling Dispose (or using Using statements) where allowed, but
in reality if you know that your object isn't using unmanaged resources,
then you don't have to worry about it.

-Scott
 
C

CLGan

If the object implement disposable, we better use

using(Myobject objABC = new Myobject())
{
.....
}
System will clear up all the resource after run the section code
 
S

Scott M.

But, the OP is asking if it is necessary, not just good practice and the
answer is that it is not always necessary. For example, a DataSet exposes
Dispose(), but you would only need to call it if you were loading your
DataSet from a file, not if you were loading it from a string.
 
B

Ben Voigt [C++ MVP]

Frank said:
Should we call .Dispose() every chance we get... on every object that
exposes .Dispose()... and every time we have such an object?

For example, is it true that *every* time I create a DataTable and
use it, that I should call .Dispose of the DataTable instance when
I'm done with it?

When it's done being used (not just by you but by any library you handed it
off to), yes. This is hardly the same as "every time we can call it" which
you wrote in the subject line.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top