Converting Hashtables to Generic Dictionaries

When using a dictionary you can do the following:

Hashtable hashtable = new Hashtable();
string test;
test = (string)hashtable["a"];  // test is “a”
test = (string)hashtable["c"]; // test is null

However, when converting this to a generic dictionary, it has a different expected behaviour:

Dictionary<string, string> dictionary = new Dictionary<string, string>();
string test;
test = dictionary["a"];  // test is “a”
test = dictionary["c"];  // throws KeyNotFoundException’

You can either do this:

Dictionary<string, string> dictionary = new Dictionary<string, string>();
string test;
try
{
    test = dictionary["c"];  // throws KeyNotFoundException’
}
catch
{
    test = null;
}
or use the more generic approach:

dictionary.TryGetValue( "c", out test );  // test is null

If the key is not found, then the value parameter gets the appropriate default value for the value type V;
for example, zero (0) for integer types, false for Boolean types, and null for reference types.

 

Recent Posts

Tag Cloud

No Comments