views:

254

answers:

2

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

+6  A: 

The closest platform equivalent is probably a Dictionary<K, WeakReference<V>>. That is, it's just a regular dictionary, but with the values being weak references.

John Feminella
You mixed something up, the keys have to be weak not the values, sorry just reread the question.
josefx
It says "weak keys or/and weak values". Weak values are probably preferable to weak keys -- you don't want a weak key and a strong value, because then you don't have a way to get your value back if your key expires!
John Feminella
Actually, weak keys are also very useful. For instance in caches.But they are harder to implement with just WeakReferences and Dictionary.
Daniel Sperry
That's very true. If this was a cache, though, I don't think a WeakHashMap is necessarily what you want -- there are some better alternatives.
John Feminella
For my current problem your solution is fine. I made a Dictionary<int, WeakReference>, and I might iterate over the key pairs from time to time to prune the collected values. However if I were more concerned with performance or concurrency this pruning would not be a such a good idea. WeakHashMap like (weak keys) also would not work. I asked the question trying to find the gold mine: some .net namespace with all nice gc aware collections and classes that I might need.In my previous project we built a STM system in java, there almost every possible combination of references were necessary.
Daniel Sperry
+2  A: 

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 in .Net 4.0, there is a structure available called ConditionalWeakHashTable in the Runtime.CompilerServices namespace that also does the trick.

JaredPar
I recently came across this blog post It states "I'll save [compaction] for next time". I'm interested how compaction would be done, but I could not find "next time" :-( is it available anywhere? Here is what I came up with on my own: http://stackoverflow.com/questions/2047591
dtb