Jump to content
  • Advertisement

Archived

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

Yratelev

C# foreach with Hashtables

This topic is 5287 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
Advertisement
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.

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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!