TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Generic Hashtable

Well, not exactly. A generic Dictionary is a nice alternative to Hashtable because a Hashtable takes System.Object as key and value types. Using a generic dictionary, I can set the type of key and value (in this case the key is a string and the value is an integer). Unfortunately, unlike Hashtable which returns null if an item is not found, a generic Dictionary will throw an exception. But you can avoid that happening by using TryGetValue(). Pretty slick!

Dictionary<string, int> d = new Dictionary<string, int>();

d.Add("test1", 1);

d.Add("test2", 2);

 

int x;

bool b = d.TryGetValue("test2", out x);

Console.WriteLine("{0}, {1}", b, x);


Digg!

posted on Wednesday, July 06, 2005 10:22 AM

Feedback

# re: Generic Hashtable 2/12/2007 12:24 AM Remy Blaettler

Thanks, exactly what I was looking for! Funny that they didn't just make the HashTable a generic...