Let's say we need to keep track of objects that have been instantiated in our application. The "Identity Map" pattern does just this and we can implement it with a simple Dictionary<TKey, TValue>. However, we need a different dictionary for each type of object which can become cumbersome to keep track of. Let's look at a technique by which we can have all of our pools in one aggregate pool object.
The trick is maintaining type-safety. At the gooey center of our aggregate pool we won't necessarily be type-safe, but everything on the crunchy exterior that is publicly available to consuming code will be. Let's say all of our object have a key property which is an Int32. If this is the case, we can just build a type-safe wrapper for a Dictionary<Type, Dictionary<Int32, Object>> where the interior Object is of the type of the key of the outer dictionary.

In order to keep things safe, we'll have to make the instance of the nested dictionary pool private. Then to safely add an item to the pool, we must first check if there is a "inner" dictionary before we execute the add method.
private Dictionary<Type, Dictionary<Int32, Object>> m_pool;
public void AddItem<T>(Int32 pID, T value)
{
Type myType = typeof(T);
if (!m_pool.ContainsKey(myType))
{
m_pool.Add(myType, new Dictionary<int, object>());
m_pool[myType].Add(pID, value);
return;
}
if (!m_pool[myType].ContainsKey(pID))
{
m_pool[myType].Add(pID, value);
return;
}
m_pool[myType][pID] = value;
}
When we remove an object from the pool, we'll have to again check that the "inner" dictionary exists:
henrique telesPosted Aug 3, 2010, 5:23 AM
Very good example! thank you! Henrique Teles http://www.bhone.com.br Desenvolvimento de Sistemas Web
D MontalPosted Oct 23, 2009, 5:34 PM
Hi, I don't see that this code implements an "Identity Map" pattern. Maybe some type of cache. An Identity Map keeps a record of all objects that have been read from the database in a single business transaction. How this code do that? I am looking for an Identity Map implementation in c#. I saw implementation in java using static ThreadLocal. Do you known an implementation for that? Thanks Diego
Kevin Alexandre MarchandPosted Sep 23, 2009, 10:40 AM
Hi, I'm getting a nullReferenceException when tying to access the GetItems function. example foreach (Animal a in col.GetItems<Animal>()) { Console.WriteLine(a.ToString()); }
Bonolo DichabePosted Feb 13, 2009, 5:10 PM
This example is very clear and it allows a person to understand dictionary generics more clearly.