Why Dispose method can not be virtual

G

Guest

In MSDN example for IDisposable, it has the followin
----------------------------------------------------------------------------
// Implement IDisposable
// Do not make this method virtual
// A derived class should not be able to override this method
public void Dispose(

Dispose(true)
// This object will be cleaned up by the Dispose method
// Therefore, you should call GC.SupressFinalize t
// take this object off the finalization queue
// and prevent finalization code for this objec
// from executing a second time
GC.SuppressFinalize(this)

----------------------------------------------------------------------------

Could someone explains me why "Dispose method can not be virtual, A derived class should not be able to override this method." I just want to do this in the base clas

public void Dispose(

DoDispose()


protected virtual void DoDispose(



And the derived class could override DoDispose method to do its own clean up work

Is this acceptable? Or this is confilict with "Dispose method can not be virtual,..." I just want to know the reason.

Thank you very very much
 
K

Kevin P. Fleming

Bonnie said:
Is this acceptable? Or this is confilict with "Dispose method can not be virtual,..." I just want to know the reason.

If the base class has any implementation, and is allocating resources
that need to be cleaned up at Dispose() time, then having a virtual
Dispose method that's overridden by an inheriting class would stop them
from being released, unless the inheriting class specifically calls the
base's Dispose method. Better to be safe than sorry here, and let each
class implement IDisposable itself.
 
J

Jon Skeet [C# MVP]

Bonnie said:
Could someone explains me why "Dispose method can not be virtual, A
derived class should not be able to override this method." I just
want to do this in the base class

public void Dispose()
{
DoDispose();
}

protected virtual void DoDispose()
{
}

And the derived class could override DoDispose method to do its own
clean up work.

Is this acceptable? Or this is confilict with "Dispose method can not
be virtual,..." I just want to know the reason.

You certainly *can* make Dispose virtual. Whether you should or not is
a different matter.

Personally, I can't see that making Dispose virtual is any worse than
making Dispose(bool) virtual - derived classes which override Dispose
(bool) will still have to call base.Dispose(bool) in order to work
properly.

The only thing achieved in the example is to ensure that
SuppressFinalize is called exactly once.
 

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