Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent for Java WeakHashMap class in C#?

Is there a C# class that provides map with weak keys or/and weak values? Or at least WeakHashMap like functionality.

like image 458
Daniel Sperry Avatar asked Jan 17 '10 15:01

Daniel Sperry


People also ask

What is WeakHashMap class in Java?

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.

What is the difference between HashMap and WeakHashMap?

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.

Is WeakHashMap synchronized?

Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.

What is true about a WeakHashMap garbage collector?

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.

Does WeakHashMap allow null keys?

WeakHashMap would accept null keys, but would never remove that entry again.


1 Answers

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.

like image 94
JaredPar Avatar answered Sep 28 '22 07:09

JaredPar