The death condition in C#

 

There is a very interesting use of the destructor, even if it’s not called every time. That use is the verification of the death condition2 of an object. At the point that you’re no longer interested in an object—when it’s ready to be cleaned up—that object should be in a state whereby its memory can be safely released. For example, if the object represents an open file, that file should be closed by the programmer before the object is garbage collected. If any portions of the object are not properly cleaned up, then you have a bug in your program that could be very difficult to find. The value of the destructors is that it can be used to discover this condition, even if the destructor isn’t always called. If one of the destructors happens to reveal the bug, then you discover the problem, which is all you really care about.

 

Here’s a simple example of how you might use it using a destructor to detect an object thathasn't been properly cleaned up.

 

class Employee

{

        bool checkedOut = false;

        internal Employee(bool checkOut)

        {

            checkedOut = checkOut;

        }

        internal void CheckIn()

        {

            checkedOut = false;

        }

        ~Employee()

        {

            if (checkedOut)

                System.Console.WriteLine("Error: checked out");

        }

}

 

public class DeathConditionExp

{

        public static void Main()

        {

            Employee novel = new Employee(true);           

            novel.CheckIn();           

            new Employee(true);           

            System.GC.Collect();

        }

}

 

The death condition is that all Employee objects are supposed to be checked in before they are garbage-collected, but in Main( ) a programmer error doesn’t check in one of the books. Without the destructor’s validation of the death condition, this could be a difficult bug to find.