#733 – How to Tell If an Object Has Been Garbage Collected

You normally can’t tell whether an object has been garbage collected by using some reference to the object–because once you have a reference to the object, it won’t be garbage collected.

You can instead create a weak reference to an object using the WeakReference object.  The weak reference is one that won’t be counted as a reference, for purposes of garbage collection.

In the code below, we check before and after garbage collection to show that a Dog object is garbage collected.

            Dog dog = new Dog("Bowser");

            WeakReference dogRef = new WeakReference(dog);

            dog = null;




About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #733 – How to Tell If an Object Has Been Garbage Collected

  1. Pingback: #734 – Accessing the Original Object Referenced through a WeakReference « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: