#736 – Target of a WeakReference Will Be null after Garbage Collection

You can create a WeakReference object that refers to a regular reference-typed object and lets you discover whether the original object has been garbage collected or not.  The IsAlive property of the WeakReference can be used to determine whether the object has been garbage collected or not.  (Although a value of true can’t be trusted).

You can use the Target property of the WeakReference to reference the original object, if it’s still alive.  However, if the original object has already been garbage collected, the Target property will be null and you can then no longer reference the original object.

            Dog dog = new Dog("Bowser");

            WeakReference dogRef = new WeakReference(dog);

            // Bowser gets garbage collected
            dog = null;
            GC.Collect();

            Console.WriteLine(string.Format("Object still alive: {0}", dogRef.IsAlive));

            // dogRef.Target will now return null, since
            // original Dog object was garbage collected
            Dog origDog = (Dog)dogRef.Target;
            if (origDog != null)
                origDog.Bark();
            Console.WriteLine("Bowser is gone..");

736-001

Advertisements