The equivalent to a C++ destructor is IDisposable
and the Dispose()
method, often used in a using
block.
See http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
What you are calling a destructor is better known as a Finalizer
.
Here's how you would use IDisposable. Note that Dispose()
is not automatically called; the best you can do is to use using
which will cause Dispose()
to be called, even if there is an exception within the using
block before it reaches the end.
public class MyClass: IDisposable
{
public MyClass()
{
//Do the work
}
public void Dispose()
{
// Clean stuff up.
}
}
Then you could use it like this:
using (MyClass c = new MyClass())
{
// Do some work with 'C'
// Even if there is an exception, c.Dispose() will be called before
// the 'using' block is exited.
}
You can call .Dispose()
explicitly yourself if you need to. The only point of using
is to automate calling .Dispose()
when execution leaves the using
block for any reason.
See here for more info: http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx
Basically, the using
block above is equivalent to:
MyClass c = new MyClass();
try
{
// Do some work with 'C'
}
finally
{
if (c != null)
((IDisposable)c).Dispose();
}