Su Llewellyn
Su Llewellyn

Reputation: 2938

How to enumerate a Hashtable with foreach in C#

I'm trying to enumerate a Hashtable which is defined as:

private Hashtable keyPairs = new Hashtable();

foreach (SectionPair s in keyPairs)
{
    if (s.Section == incomingSectionNameVariable)
    {
        bExists = true;
        break;
    }
}
// more stuff here

But I get an error from Visual Studio 2013, "InvalidCastException was unhandled". Using a Dictionary, notwithstanding, I'm interested in knowing why I'm getting this error.

Upvotes: 15

Views: 44361

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477704

As you can read in the Remarks section of the Hashtable class, the objects you enumerate are DictionaryEntrys. So you will have to rewrite it to something like:

foreach(DictionaryEntry s in keyPairs) {
   //Is Section the Key?
   if(s.Key == incomingSectionNameVariable) {
      bExists = true;
      break;
    }
}

A DictionaryEntry has a Key and Value element (that are of course the keys and the values in the Hashtable. Both are Objects since a Hashtable is not generic and thus the compiler can not know what the type of the Key and/or Value is.

I advice you however to use a Dictionary<TKey,TValue> since here you can specify the type of the Key and Value. In that case an example could look like:

private Dictionary<string,int> keyPairs = new Dictionary<string,int>();

foreach( KeyValuePair<string,int> kvp in keyPairs) {
    //do something with kvp
}

But here kvp.Key will be a string so you don't have to cast it and it is safer to use.

Upvotes: 30

Related Questions