DataAdapter da = new DataAdapter();
// do something with da
da.Dispose();
Is that the proper way to destroy an object when I am done with it? Or
should I be doing:
da = Nothing;
or a combonation of both? I want to make I am getting rid of my objects
correctly to free up memory on the server.
DataAdapter inherits from Component, which in turn implements
IDisposable and the disposable pattern (just like forms do). Component
surfaces a protected, virtual Dispose(bool) method that is called from
both IDisposable.Dispose and Finalize. DataAdapter and SqlDataAdapter
override the protected Dispose method and do some internal cleanup.
In general, as soon as you are done using a DataAdapter, or any other
class derived from Component, you should call Dispose. If a class
implements IDisposable, it is an indication by the class' designer that
you should call Dispose when you are done using instances of the class.
If you don't, its not the end of the world. The GC will call Finalize
eventually on the object. However, for optimum memory usage, IDisposable
objects should be disposed as soon as possible.
If you use interfaces frequently, often times you may not know whether
an object implements IDisposable. For example, I like to write generic
code that deals with the data interfaces (IDbConnection, IDbDataAdapter,
etc), and these interfaces don't descend from IDisposable. In this case,
you can mix a using statement with a cast.
IDbConnection connection = ConnectionFactory.Create()
using(connection as IDisposable)
{
connection.Open();
...
}
The IL generated by a using statement checks for null before calling
Dispose. If the object implements IDisposable, Dispose is called.
Otherwise, the using statement acts as a NOP.
One last gotcha: dropping a component on a form does not guarantee that
Dispose will get called for that object. Components that implement a
magical constructor (public ImageList(IContainer container)) are added
to the components container of the form, and are automatically disposed
by the boilerplate Dispose method of your derived form. However, the
data classes don't have this constructor, so you have to add a Dispose
call manually.
PS: This seems like a flaw to me. Any component with a non-trivial
dispose method should have this special constructor. Most of the
components don't.
H^2