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!