destructor

G

Guest

Hi,

sometimes I see code like the following:
~MyObject(){..}

Is a destructor in C# available? Should not be the cleanup logic be a part
of Dispose()?

Thanks
Christian
 
S

Simon Tamman

Yes it is a destructor and these are available in C#. It will act as an
additional call when Finalize is called on the object by the GC.

It will basically turn the destructor into this:

public override void Finalize()
{
// your destructor code
base.Finalize();
}

base.Finalize() will also call Dispose(true) if the method exists on the
object. It will do this regardless of if there is a destructor provided or
not.
It's usually best to put the tidy up code in a disposing method

public void Dispose(bool disposing)
{
if(disposing)
{
// clean managed resources
}
else
{
// clean unmanaged resources
}
}

For more in-depth information you can read this article here:

http://www.codeproject.com/useritems/idisposable.asp
 
B

Ben Voigt

Simon Tamman said:
Yes it is a destructor and these are available in C#. It will act as an
additional call when Finalize is called on the object by the GC.

No it's not a destructor (it's not deterministic and it is independent of
scope). You have described the finalizer correctly though.
 
J

Jon Skeet [C# MVP]

Ben Voigt said:
No it's not a destructor (it's not deterministic and it is independent of
scope). You have described the finalizer correctly though.

<trivia>
Annoyingly enough, in the first version of the C# spec it was called a
destructor. Fortunately they changed it for C# 2.0 as it caused
confusion.
</trivia>
 

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