Simple question about dispose() and = null

  • Thread starter Thread starter Joey
  • Start date Start date
J

Joey

Hi,

I have come across codes like this

if(dbConn != null)
{
dbConn.dispose();
}

and sometimes like

dbConn.dispose();

if(dbConn != null)
{
dbConn = null;
}

I was wondering what is the correct way of cleaning up?

Thanks

Joey
 
Joey said:
I was wondering what is the correct way of cleaning up?
Class instances often encapsulate control over resources that are not
managed by the runtime, such as database connections and similar. You
can provide implicit control over how these resources are managed by
implementing a destructor in the class. The garbage collector calls this
method at some point after there are no longer any valid references to
the object.

If an external resource is scarce or expensive, you might want to
provide the ability to explicitly release these resources before the
garbage collector frees the object. To provide explicit control,
implement the IDisposable interface.

If you implement IDisposable, you should provide implicit cleanup using
a destructor.

Here is an example of a best-practice implementation of IDisposable:
public class MyClass : IDisposable {
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing) {
if (disposing) {
// Free other managed objects.
}
// Free unmanaged objects and set large fields to null.
}

~MyClass() {
Dispose (false);
}
}

For more info on when you use destructors and when to implement the
IDisposable interface see
http://msdn.microsoft.com/library/d.../en-us/cpgenref/html/cpconFinalizeDispose.asp

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 
Hi, Joey!

class MyDisposableClass : IDisposable
{

private SqlConnection _connection;
....

public void Dispose()
{
this.Dispose( true );
GC.SuppressFinalize( this );
}

private void DisposeConnection()
{
if ( _connection == null ) return;
_connection.Dispose();
_connection = null;
}

protected virtual void Dispose( bool disposing )
{
if ( disposing ){
DisposeConnection();
}
}

~MyDisposableClass()
{
this.Dispose( false );
}

}
 
If you implement IDisposable, you should provide implicit cleanup using
a destructor.

That's not always true. If you implement IDisposable in order to call
Dispose on other objects, there's usually no need for a destructor.

If you contain unmanaged resources directly, *that's* the place for a
destructor.
 
dbConn.dispose();

if(dbConn != null)
{
dbConn = null;
}

This code is malformed. There is no point checking to see whether dbConn
is null after calling Dispose. If dbConn is null, then the Dispose call
is going to raise a null pointer exception. Dispose itself is not going
to set the dbConn variable to null.

The other code example made sense. Or you could do this:

if(dbConn != null)
{
dbConn.Dispose();
dbConn = null;
}

The if statement isn't necessary if you can find a way to employ a using
statement.

H^2
 
Back
Top