Invalid Cast exception with hashtable

Posted on 2005-05-17
Last Modified: 2008-02-01
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.
Question by:djs120
    LVL 23

    Accepted Solution

    foreach(DictionaryEntry e in expCollection)
          TRI.FarmSelect.Expense item = e.Value as TRI.FarmSelect.Expense;
          if (item != null)
                / * do stuff */

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

    LVL 1

    Author Comment

    Second suggestion worked like a charm (didn't try the first one).  Thanks!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Hire Top Freelancers to Complete C# Projects

    Source the talented Expert Exchange community
    for top quality work on your C# projects.

    Hire the best. Collaborate easily. Get quality work.

    Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
    Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now