#734 – Accessing the Original Object Referenced through a WeakReference

You can create a WeakReference instance that refers to an object and then use the WeakReference to determine whether the object has been garbage collected.

You can also refer back to the original object referenced by the WeakReference using its Target property.

            Dog dog = new Dog("Bowser");

            WeakReference dogRef = new WeakReference(dog);

            Dog origDog = (Dog)dogRef.Target;

When you refer to the original object in this way, you add a reference to it, which means that it won’t get garbage collected.

            Dog dog = new Dog("Bowser");

            WeakReference dogRef = new WeakReference(dog);

            Dog origDog = (Dog)dogRef.Target;

            dog = null;
            GC.Collect();

            // Bowser still alive at this point, since we still have
            // a reference to him.

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

734-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.

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: