Is there a C# class that provides map with weak keys or/and weak values? Or at least WeakHashMap like functionality.
WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap. This class provides the easiest way to harness the power of weak references.
A WeakHashMap has key-value pairs i.e. it is quite similar to a HashMap in Java. A difference is that the WeakHashMap object that is specified as a key is still eligible for garbage collection. This means that the garbage collector has dominance over the WeakHashMap.
Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn't contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.
WeakHashMap would accept null keys, but would never remove that entry again.
In .Net 3.5 and below, there is no such structure available. However I wrote up one for a side project and posted the code at the following location.
Starting .NET 4.0, there is a structure available called ConditionalWeakTable
in the Runtime.CompilerServices namespace that also does the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With