.NET doesn't use destructors, it uses Finalizers. The main difference being
that with a destructor, you know when it is going to occur and with
Finalizers you don't.
Because .NET uses Garbage Collection and non-deterministic finalization for
objects stored on the managed heap, you can't know when (or technically
"if") an object will be removed from memory. That is the moment in which
your Finalizer will fire. Instead, you should write any cleanup code you
have in the class's Dispose() method and simply call Dispose when your code
no longer is using the object.
FYI - Decaring your instance with CSharp's "using" statement, causes that
object to automatically call its' Dispose method when the using block is
complete.
-Scott
> Because .NET uses Garbage Collection and non-deterministic finalization
> for objects stored on the managed heap, you can't know when (or
> technically "if") an object will be removed from memory. That is the
> moment in which your Finalizer will fire. Instead, you should write any
> cleanup code you have in the class's Dispose() method and simply call
> Dispose when your code no longer is using the object.
It should be added that you class should implement the IDisposable
interface, not just add a Dispose method. This should only be used for
objects that have a need for it. Usually that need is unmanaged resources or
the use of managed objects that use unmanaged resources (eg Pen or Brush).
Michael
Scott M. - 16 Jan 2008 01:23 GMT
And, to add upon that...
If you class isn't using unmanaged resources, but does need clean up of .NET
resources, that clean up should either occur at the end of the method that
uses the resources or in a separate cleanup type method (i.e. "close").
-Scott
>> Because .NET uses Garbage Collection and non-deterministic finalization
>> for objects stored on the managed heap, you can't know when (or
[quoted text clipped - 10 lines]
>
> Michael
Eitan - 16 Jan 2008 02:05 GMT
Scott & Michael,
Thanks
Eitan
> > Because .NET uses Garbage Collection and non-deterministic finalization
> > for objects stored on the managed heap, you can't know when (or
[quoted text clipped - 9 lines]
>
> Michael