2.18. The Class Destructor

C# supports a nondeterministic destructor method, but its use is discouraged. It is nondeterministic in two respects. The first is that we are unable to predict when the destructor is called, or even if it is called. Second, we are unable to predict the order of destructor invocations. From a performance standpoint, classes with destructors have significantly greater overhead in their interaction with the garbage collector.

A destructor—or some sort of finalization routine—is necessary when a class object acquires unmanaged resources during its lifetime and we wish those resources to be released following a last use of that object. Resources might include window or file handles, or database connections. By convention, ...

Get C# Primer: A Practical Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.