• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 411
  • Last Modified:

Invalid Cast exception with hashtable

I have the following code.  expCollection is a hashtable that contains a collection of classes of type TRI.FarmSelect.Expense:

private void getBudgetItemPrices(Hashtable expCollection, int budgetID, int regionCode)
{
      /* Loop through expenses collection and for each expense find prices/costs and assign */
      foreach(TRI.FarmSelect.Expense expense in expCollection)
      {
            if (DB.getBudgetItemCost(Response, budgetID, regionCode, expense))
            {
                  /* do stuff... */
            }
      }
}

I get a runtime error "Specified cast is not valid" in the foreach statement.  I am positive that the expCollection contains classes of the Expense type.  Why would it give this runtime error? Thanks.
0
djs120
Asked:
djs120
1 Solution
 
b1xml2Commented:
foreach(DictionaryEntry e in expCollection)
{
      TRI.FarmSelect.Expense item = e.Value as TRI.FarmSelect.Expense;
      if (item != null)
      {
            / * do stuff */
      }
}

or
foreach(TRI.FarmSelect.Expense expense in expCollection.Values)
{

}
0
 
djs120Author Commented:
Second suggestion worked like a charm (didn't try the first one).  Thanks!
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now