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
by Krishnan
10 Nov 2008 at 18:34
Hey dude,
I was just browsing your website and I noticed this entry. Although I know this was written a long time back, I wanted to comment on this.
Probably, you have already realised this. The indexer in a Dictionary collection can be used to Add AND Update the collection. So if you have something like –
Dictionary keyVal = new Dictionary();
keyVal[1] = “Hello”;
This should work even though the key [1] does not exist. The indexer adds the entry if it does not find the key and updates the value if it does. Im not sure when you get the exception.
by verma
10 Nov 2008 at 19:14
Hey Krishnan, How are you?
I think you’re right. I primarily work with v2.5 of the framework. May be that’s why I still see it. I think this has been changed with more recent versions of the framework.
by taelor
13 May 2009 at 20:44
Nice beats, nice post. Looks more Rubyish this way. Now we just need dynamic values in the Dictionary and I’ll be happy!
$)