SiteMap  | About    

What's a weak reference

A weak reference is a way to have some pointer to an object that does have any reference (strong reference). In .NET, any normal reference to another object is a strong reference . That is, when you declare a variable of a type that is not a primitive/value type, you are declaring a strong reference.

The Garbage Collector (GC) start cleaning memory for objects that do not have any reference. The GC (garbage collector) cannot collect an object in use by an application while the application's code can reach that object. If you hold a strong reference to an object directly in a static variable or in a local variable, it can't be collected. Also, if such an object holds references to other objects, those other objects can't be collected either.

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. When we need to access a weak referenced object we can just check if the object is alive and then access it if the object is alive at all. Most objects that are referenced must be kept in memory until they are unreachable. But with WeakReference , objects that are referenced can be collected. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.

When should weak references be used?

You can use weak references whenever you want to have a reference to an object without keeping the object alive yourself. (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.