C# foreach with Hashtables
Hi, Im having a bit of trouble getting my stuff out of hashtables
im using:
Bob bob = new Bob();
Hashtable vHash = new Hashtable();
vHash.Add(bob);
foreach(Bob b in vHash)
b.ABobMemberFunction();
But I get a System.InvalidCastException and when i change it to
foreach(object b in vHash)
b.GetType()
it turns out the type is System.Collections.DictionaryEntry, and I cant get to the Bob object.
Any ideas
thanks
Yratelev
An entry in the hashtable is of the type DictionaryEntry (an entry is a key, value pair). You can use the according properties of the DictionaryEntry to access what you want.
Hello,
You possibly shouldn''t be using Hashtables if you want to iterate through the list like that. An ArrayList might be a better choice.
However, to get your desired effect, try this:
foreach (DictionaryEntry entry in vHash)
{
Bob b = (Bob) entry.Value;
}
You possibly shouldn''t be using Hashtables if you want to iterate through the list like that. An ArrayList might be a better choice.
However, to get your desired effect, try this:
foreach (DictionaryEntry entry in vHash)
{
Bob b = (Bob) entry.Value;
}
quote:Original post by Yratelev
vHash.Add(bob);
Well, the hashtable does not have an Add method with that signature. You always have key-value pairs.
Furthermore: you can iterate through either the keys or the values by using the Keys or Values property, e.g.
foreach(Bob b in vHash.Values) { b.ABobMemberFunction();}
If the "Bob"s are keys in the hashtable use vHash.Keys instead
Regards,
Andre (VizOne) Loker
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement