IDisposable with an abstract class?

B

bubby

I have a database interface class (an abstract class) that has two
derived classes that work with two different types of databases. If
the dervied classes have managed, and unmanged resources and the base
(abstract) class doesn't, how do I implement the IDisposable interface?
Do I have the base (abstract) class inherit from IDisposable? If I
do, how will that work since the class is abstract and no instance is
actually created. Or, should I just implement the interface
IDisposable off of the two derived classes?

Thanks!

bubby
 
N

Nicholas Paldino [.NET/C# MVP]

bubby,

In this case, you would implement IDisposable on the abstract class. On
your abstract class, you would have a method with the following signature:

protected virtual void Dispose(bool disposing)
{
}

This is what would be overridden in base classes to dispose their
resources. When implementing this, the boolean disposing value is going to
tell you whether or not you are being called from the finalizer or from the
Dispose method.

Check out the article on MSDN titled "Implementing Finalize and Dispose
to Clean Up Unmanaged Resources", located at (watch for line wrap):

http://msdn.microsoft.com/library/d.../en-us/cpgenref/html/cpconFinalizeDispose.asp

It goes into great detail how you should implement IDispose on your base
class, as well as override the protected Dispose method in your derived
classes.

Hope this helps.
 
I

iulianionescu

Probably this is a good way:

In the abstract class (called MyAbstractClass):

bool disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
// Dispose managed resources.
}
// Dispose unmanaged resources here.
}
disposed = true;
}
~MyAbstractClass()
{
Dispose(false);
}


In the 2 derived classes:

protected override void Dispose(bool disposing)
{
if(disposing)
{
// Dispose managed resources.
}
// Dispose unmanaged resources here.
base.Dispose(disposing);
}

I hope this helped.
 
B

bubby

Will this method work with an abstract class? This differs from a
regular class where because no instance is actually created. If that
is the case, how will the dispose method and/or the destructor ever get
called (ie. nothing was created)?
 

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