Equivalent to a C ++ destructor, this is IDisposable and the Dispose() method, which is often used in the using block.
See http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
What you call a destructor is better known as Finalizer .
Here you can use IDisposable. Note that Dispose() not called automatically; the best thing you can do is use using , which will call the Dispose() call, even if there is an exception in the using block before it reaches the end.
public class MyClass: IDisposable { public MyClass() {
Then you can use it as follows:
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 if you need to. The only using point is to automate the call to .Dispose() when execution for some reason leaves the using block.
See here for more information: http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx
Basically, the using block above is equivalent:
MyClass c = new MyClass(); try { // Do some work with 'C' } finally { if (c != null) ((IDisposable)c).Dispose(); }
source share