TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
SeethaLakshmi Raja
NA
6
0
Generic dictionary with weakreference value
Nov 18 2008 6:17 AM
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.
Reply
Answers (
2
)
WebParts
abstract class and serialization