April 5, 2011

Use TryGetValue instead of ContainsKey

See these pages for more info:
C# TryGetValue
C# TryGetValue Method

Basically, instead of
private Dictionary  xxxCache = 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;
}
use
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