Palaniraj
Palaniraj

Reputation: 1

In c# ,hashtable key and value are getting an error

Hashtable hsh = new Hashtable();
hsh.Add("glc", "goldchild");


foreach(DictionaryEntry e in hsh) {
    Console.WriteLine(e.Key, e.Value);
}

Upvotes: 0

Views: 406

Answers (1)

NotFound
NotFound

Reputation: 6157

A Hashtable is not strongly typed. Therefore the keys and values you save to it will be casted into object. Once you get the value out of it you need to cast it back to a string. You could do a few things, but here's the ones you should be interested in.

1) Try casting it back to string:

Console.WriteLine(e.Key as string + ":" + e.Value as string);

2) Instead of using Hashtable use the equivalent strongly typed Dictionary. This should be preferable as you know what types you are working with and you'll have type safety.

That means your IDE will warn you upfront if you are trying to use the variables in ways that don't fit the type, while without type safety you could get unexpected exceptions at runtime due to casting errors that are invalid.

Dictionary<string, string> hsh = new Dictionary<string, string>();
hsh.Add("glc", "goldchild");

foreach (KeyValuePair<string, string> e in hsh)
{
    Console.WriteLine(e.Key + ":" + e.Value);
}

Upvotes: 2

Related Questions