15

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.

1
  • 7
    Are you sure all the elements in keyPairs can be casted to SectionPair? Also, you should not use non-generic Hashtable. Move to generic HashSet<T> to get compile-time type safety. Commented Jan 5, 2017 at 21:48

1 Answer 1

29

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.

1
  • 1
    That's just what I needed to understand. May the wind always be at your back. -su Commented Jan 5, 2017 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.