#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. Seraph says:

    Hi, Sean, is this true? I have tried one in Visual studio 2015, the weakreference type is not null.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: