Deciding When to Use Weak References in .NET | CodeGuru

Deciding When to Use Weak References in .NET

.NET WeakReference Example The .NET WeakReference Class represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection. Now, let’s see an example. Create a console application from Visual Studio and name it MyWeakReference. Create a WeakReference object and pass an object reference to the constructor call. […]

Written By
Tapas Pal
Tapas Pal
Aug 7, 2018
2 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

.NET WeakReference Example

The .NET WeakReference Class represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection. Now, let’s see an example. Create a console application from Visual Studio and name it MyWeakReference.

Create a WeakReference object and pass an object reference to the constructor call. In the following example, I have used the StringBuilder object.

static WeakReference myweakerenceobject;
myweakerenceobject = new WeakReference(new StringBuilder("My weak
   reference object."));

During execution, in the middle of the program, the garbage collector is executed by using GC.Collect. After this call, the object pointed to by the WeakReference no longer exists. After the call, I have checked if the object is still alive. Refer to the following code snippet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWeakReference
{
   class Program
   {
      static WeakReference myweakerenceobject;
      static void Main(string[] args)
      {
         myweakerenceobject = new WeakReference(new
            StringBuilder("My weak reference object."));
         if (myweakerenceobject.IsAlive)
         {
            Console.WriteLine((myweakerenceobject.Target as
               StringBuilder).ToString());
         }
         GC.Collect();
         // Check if still alive after GC call.
         if (myweakerenceobject.IsAlive)
         {
            Console.WriteLine("Object Alive");
         }
         Console.WriteLine("[I'm Done]");
         Console.Read();
      }
   }
}

The IsAlive property mentioned in the preceding code is an important property on the WeakReference type. This Boolean property indicates whether or not the object pointed to by the WeakReference has been collected.

I have also used the Target property in the code snippet. That returns an object that contains the reference to the instance I stored in the WeakReference. However, if the original object has already been garbage collected, the Target property will be null and then you can no longer reference the original object.

What Are the Differences Between Weak and Strong References?

The difference between a weak and a strong reference to an object is that, while the former still allows the garbage collector to reclaim the memory occupied by that object, a strong reference to an object doesn’t allow the garbage collector to reclaim the memory occupied by that object if the object is reachable.

Should We Use WeakReference?

A developer should use long weak references only when necessary because the object is unpredictable after finalization. We should avoid using weak references to small objects because the pointer itself may be as large or larger. Instead of weak references, we should develop an effective caching policy in an application.

WeakReference is often used for implementing Weak Events. Event handlers are a frequent cause of memory leaks, particularly when you have a long-lived service with events that multiple instances subscribe to.

Advertisement

Conclusion

That’s all for today. The following references are for for further study.

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.