Alright, here we go. After a long long long time I have decided to yet again try and maintain a blog.
The other day at work I was trying to use .NET’s Dictionary class to create a hierarchical structure which allows me to do something like this:
torqueInfo[eAvatarGender.male][eJointName.elbow][eJointDirection.extension]
= new TorqueCurves(eAvatarGender.male, eJointName.elbow, eJointDirection.extension);
torqueInfo has been defined as:
Dictionary<eAvatarGender, Dictionary<eJointName, Dictionary<eJointDirection, TorqueCurves>>> torqueInfo;
Using the dictionary object this way would help me reduce my coding clutter to just 3 look-ups instead of coding a 3 level conditional switch (one of the straightforward ways of doing it).
The problem with this is that unlike C++ std::map objects, if a .NET dictionary doesn’t contain the specified key it throws an exception.
Dictionary<int, string> keyVal = new Dictionary<int, string> ();
keyVal [5] = "Hello"; // exception
keyVal.Add (5, "Hello"); // OK
Filling up such a construct with an Add method could have easily turned into a nightmare. To tackle this problem, I created my own little dictionary class which could handle unknown keys and allow the programmer to easily populate a complex construct like I mentioned above. Here’s what the class looks like:
public class SmarterDictionary<TKey, TValue> where TValue : new ()
{
Dictionary<TKey, TValue> keyVal = new Dictionary<TKey,TValue> ();
// access operator is all we need!
public TValue this[TKey key] {
get {
if (!keyVal.ContainsKey(key))
keyVal.Add(key, new TValue ());
return keyVal[key];
}
set {
keyVal[key] = value;
}
}
}
HTH