Unsure about destructor & IDisposable for C#

  • Thread starter Thread starter Trevor Balcom
  • Start date Start date
T

Trevor Balcom

I would like to do things when my object goes out of scope, like
disconnect TCP/IP streams, serialize collections to files and so on... Would
I implement my cleanup code in Dispose() ?

Is this correct?


class A : IDisposable
{
A()
{
}

~A()
{
Dispose();
}

public void Dispose()
{
//clean up stuff here
}
}
 
That is partially correct. Check out the docs for how MS implements
IDisposable in their objects. The key thing is that if the Dispose
method is called, that you also call GC.SupressFinalize(). You will
also need a flag to indicate that the Dispose method was called vs the
finalizer.

Jonathan Schafer
 
Back
Top