Generic Weak dictionary

Nov 18 2008 12:46 PM

Please help me again.
This is the weak dictionary i have created. It is compiling correctly. But when i test it with GC.Collect(), i can still refer to the weak reference values even after calling GC.Collect() method. How is it possible? What is wrong in my code.

<pre>namespace TryWeakDictionary{
    public class WeakReference&lt;T&gt; : WeakReference {
        public WeakReference(T val)
     : base(val, false) {
        }
    }

    public class WeakDictionary&lt;TKey, TValue&gt; : IDictionary&lt;TKey,TValue&gt; {
        private Dictionary&lt;TKey, WeakReference&lt;TValue&gt;&gt; weakDictionary = new
                   Dictionary&lt;TKey, WeakReference&lt;TValue&gt;&gt;();
  
        public void Add(TKey key, TValue value) {
            WeakReference&lt;TValue&gt; weakRef = new WeakReference&lt;TValue&gt;(value);
     this.weakDictionary.Add(key, weakRef);
        }

        public void Clear() {
            this.weakDictionary.Clear();
 }

        public bool ContainsKey(TKey key) {
     return this.weakDictionary.ContainsKey(key);
        }

        public void Remove(TKey key) {
     this.weakDictionary.Remove(key);
        }

        public bool TryGetValue(TKey key, out TValue value) {
     WeakReference&lt;TValue&gt; weakReference;
     if (this.weakDictionary.TryGetValue(key, out weakReference) &amp;&amp; 
                weakReference.IsAlive) {
      value = (TValue)weakReference.Target;
      return true;
     } else {
  weakDictionary.Remove(key);
  value = default(TValue);
  return false;
     }
        }
    }
}</pre>


Answers (3)