eBabel Blog

Make a website

IDictionary[] and Hashtable results cast

22 March 2010

The following code will not build:

string hold_value;

Hashtable openWith = new Hashtable();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

foreach (DictionaryEntry de in openWith)
{
	hold_value = openWith[de.Key];
	Console.WriteLine("Key = {0}, Value = {1}", de.Key, hold_value);
};

it returns the following error:

Cannot implicitly convert type 'object' to 'string'. 
An explicit conversion exists (are you missing a cast?)
C:\Users\[Path]\Program.cs

when returning a valuable from IDictionary (e.g. when using a Hashtable) you need to use a cast operation:

hold_value = (string)openWith[de.Key];

This is probably less obvious when using a bespoke dictionary only holding values of a custom type ("Vehicle" for example) than with the more generic Hashtable data collection.

If you liked this blog post, you may want to subscribe to my news feed in your RSS reader.