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.
As you can read in the Remarks section of the Hashtable
class, the objects you enumerate are DictionaryEntry
s. 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 Object
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With