I am working on a class that deals with a lot of Sql objects – Connection, Command, DataAdapter, CommandBuilder, etc. There are multiple instances where we have code like this:
if( command != null )
{
command.Dispose();
}
if( dataAdapter != null )
{
dataAdapter.Dispose();
}
etc
I know this is fairly insufficient in terms of duplication, but it has started smelling. The reason why I think it smells is because in some instances the object is also set to null.
if( command != null )
{
command.Dispose();
command = null;
}
I would love to get rid of the duplication if possible. I have come up with this generic method to dispose of an object and set it to null.
private void DisposeObject<TDisposable>( ref TDisposable disposableObject )
where TDisposable : class, IDisposable
{
if( disposableObject != null )
{
disposableObject.Dispose();
disposableObject = null;
}
}
My questions are…
- Is this generic function a bad idea?
- Is it necessary to set the object to
null?
EDIT:
I am aware of the using statement, however I cannot always use it because I have some member variables that need to persist longer than one call. For example the connection and transaction objects.
Thanks!
I assume these are fields and not local variables, hence why the
usingkeyword doesn’t make sense.I think it’s a good idea, and I’ve used a similar function a few times; +1 for making it generic.
Technically an object should allow multiple calls to its
Disposemethod. (For instance, this happens if an object is resurrected during finalization.) In practice, it’s up to you whether you trust the authors of these classes or whether you want to code defensively. Personally, I check for null, then set references to null afterwards.Edit: If this code is inside your own object’s
Disposemethod then failing to set references to null won’t leak memory. Instead, it’s handy as a defence against double disposal.