Archived

This topic is now archived and is closed to further replies.

C# foreach with Hashtables

This topic is 4998 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites