Destroying Objects
Because C# provides garbage collection, you never need to explicitly destroy your objects. However, if your object controls unmanaged resources, you will need to explicitly free those resources when you are done with them. Implicit control over unmanaged resources is provided by 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 don't need to and should not implement a finalizer; 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 (i.e., methods that consume valuable unmanaged resources).
You can't call an object's finalizer directly. The garbage collector will call it for you.
Finalizers Versus Dispose
It is not legal to call a finalizer explicitly. Your finalizer will be called by the garbage collector. If you do handle precious unmanaged resources ...
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