Hi,
I am trying to bring generic weak reference dictionary in c# 3.0. I have created a class called WeakDictionary<TKey, TValue> which implements IDictionary<TKey,TValue>. This class has a private member as,
private Dictionary<TKey, WeakReference> weakDictionary = new Dictionary<TKey, WeakReference>();
The other methods like Add,Remove, Clear are working fine for the weakDictionary. But I could not work out the TryGetValue method. It shows the error
InvalidCastException was unhandled - Unable to cast object of type 'System.WeakReference' to type 'System.String'. on the line
value = (TValue)weakReference.Target;
I don't know how to retrieve the value. Please help me.
CODE
public bool TryGetValue(TKey key, out TValue value) {
WeakReference 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;
}
}
Thank you.