#932 – When Objects Become Eligible for Garbage Collection

In general an object can be garbage collected when it is no longer referenced by any other object or reference-typed variable.  For example, the Dog object named “Kirby” is no longer referenced in the code snippet below when the myDog variable is set to null.

            Dog myDog = new Dog("Kirby", 15);

            Dog yourDog = new Dog("Ruby", 3);

            // Kirby no longer referenced after this line executes
            myDog = null;

In practice, however, an object may become eligible for collection earlier than you think.  In the code sample above, the “Kirby” object will not be referenced at any time after the first call to the Bark method.  This means that the compiler may decide to garbage collect the “Kirby” object after the call to this method, i.e. before myDog is actually set to null.