Hi,
I am trying to bring generic weak reference dictionary in c# 3.0. I have created a class called WeakDictionary which implements IDictionary. This class has a private member as,
private Dictionary weakDictionary = new Dictionary();
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.
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.
I am trying to bring generic weak reference dictionary in c# 3.0. I have created a class called WeakDictionary
private Dictionary
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.
SeethaLakshmi RajaPosted Nov 19, 2008, 4:29 AM
As i created weak dictionary as a class library, i tested it with a console application which uses this generic weak dictionary using int for TKey and string for TValue. However, thank you very much. I created a WeakReference class separately to handle the typecast. It worked :)
AlanPosted Nov 18, 2008, 11:16 AM
As this is a runtime error, are you sure that your weak reference actually represents a string object?