Yes...
There is a pretty good example to be found here:
http://web.archive.org/web/20080212232542/http://www.robherbst.com/blog/2006/08/21/c-weakreference-example/
In your class you created two member variables:
WeakReference _weakRef = null;
Person _strongRef = null;
You created two new Person
objects (which are simple objects I just created for this example, consisting of a Name
property and some reference tracking code). Next you set the member variables to the newly created instances of the Person
objects.
_strongRef = p;
_weakRef = new WeakReference(p1);
The difference here you’ll notice that _strongRef
is just a regular normal reference, whereas _weakRef
is set to a WeakReference
object with the person object (p1)
passed in as a parameter in the constructor.
If a garbage collection were to occur, or just for testing purposes you called it yourself with:
GC.Collect();
Then the p1
target object that is held by the _weakRef
member variable should be garbage collected. You can write code to check:
if (_weakRef.IsAlive)
If the WeakReference
is still alive you can convert the WeakReference
to a strong or normal reference by using code like this:
Person p = _weakRef.Target as Person;
Now the p
reference is treated as a strong reference and won’t be collected until it is no longer used. If you wanted to keep the reference around after the scope you could set that to a member variable.