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.
1
2
3
4
5
6
7
8
| Dog myDog = new Dog("Kirby", 15);<span class="skimlinks-unlinked">myDog.Bark</span>();Dog yourDog = new Dog("Ruby", 3);<span class="skimlinks-unlinked">yourDog.Bark</span>();// Kirby no longer referenced after this line executesmyDog = 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.

