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.
- Does C# support multiple Inheritance ?
- What is Process ID ?
- How do I make a DLL in C# ?
- How many ways you can pass values to Windows Services ?
- Can we use "continue" statement in finally block ?
- What is nullable type in c# ?
- Difference between the Debug class and Trace class ?
- What is lock statement in C#
- What are dynamic type variables in C#
- What is the difference between is and as operator in C#?
- What are circular references in C#?
- What are the differences between events and delegates in C#
- Explain the types of unit test cases in C#?
- How many types of comments are there in C#?
- What are the various ways to pass parameters to a method in C#?
- What are the different ways to deploy a assembly in net?
- What does assert() method do in c#
- What is literals in C# - Constants and Literals
- What is the use of goto statement in C#
- How can JIT code be faster than AOT compiled code
- Why events have no return types in .NET
- What's the difference between a static method and a non-static method in C#
- What is C# equivalent of the vb.net isNothing function
- What are indexers in C#
- What are generics in c#