Skip to content

Generic Weak dictionary

SeethaLakshmi Raja

Asked Nov 18, 2008, 7:46 AM EST3 answers
Share
LinkedInX

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.

C#
namespace TryWeakDictionary{
    public class WeakReference<T> : WeakReference {
        public WeakReference(T val)
     : base(val, false) {
        }
    }

C#
    public class WeakDictionary<TKey, TValue> : IDictionary<TKey,TValue> {
        private Dictionary<TKey, WeakReference<TValue>> weakDictionary = new
                   Dictionary<TKey, WeakReference<TValue>>();

        public void Add(TKey key, TValue value) {
            WeakReference<TValue> weakRef = new WeakReference<TValue>(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<TValue> weakReference;
     if (this.weakDictionary.TryGetValue(key, out weakReference) &&
                weakReference.IsAlive) {
      value = (TValue)weakReference.Target;
      return true;
     } else {
  weakDictionary.Remove(key);
  value = default(TValue);
  return false;
     }
        }
    }
}

3 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Bechir Bejaoui
    +1
    Could you please explain me what for is used this code ewxactly?
    +1
  • +1
    I need it for internationalisation where all the phrases in english has its equivalent other language phrase.
    +1
  • Bechir Bejaoui
    +1
    No, my freind this is the wrong the way, .Net framework has an entire namespace nothing but for this issue it is the System.Globalization, it holds a set of very usful classes those help you to create a multi culture application
    +1