Destroying Objects
C# provides
garbage collection and thus does not need an explicit destructor. If
you do control an unmanaged resource, however, you will need to
explicitly free that resource when you are done with it. Implicit
control over this resource is provided with a Finalize( )
method (called a
finalizer), which will be called by the
garbage collector when your object
is destroyed.
The finalizer should only release resources that your object holds on
to, and should not reference other objects. Note that if you have
only managed references you do not need to and should not implement
the Finalize() method; you want this only for
handling unmanaged resources. Because there is some cost to having a
finalizer, you ought to implement this only on methods that require
it (that is, methods that consume valuable unmanaged resources).
You must never call an object’s Finalize( )
method directly (except that you can call the base class’
Finalize( ) method in your own Finalize( )). The garbage collector will call Finalize( ) for you.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access