C# TryGetValue
C# TryGetValue Method
Basically, instead of
private DictionaryusexxxCache = new Dictionary () Xxx GetEntry(Key key) { Xxx entry = null; // if entry found if (xxxCache.ContainsKey(key)) { entry = xxxCache[key] as Xxx; } else // add new entry { entry = new Xxx(...); xxxCache.Add(key, entry); } return entry; }
Xxx GetEntry(Key key)
{
Xxx entry = null;
// if entry not found
if (!xxxCache.TryGetValue(key, out entry))
{ // then add new entry
entry = new Xxx(...);
xxxCache.Add(key, entry);
}
return entry as Xxx;
}
This is assuming you do NOT want an exception to be thrown if the key is not found. I still find the first implementation as more readable
No comments:
Post a Comment