0
// this is my class object
Friend f1 = new Friend("Nazir",24);
Friend f2 = new Friend("Hamza", 24);
Friend f3 = new Friend("Abdullah", 23);

Hashtable myhash = new Hashtable();

// add this object in hashtable object
myhash.Add("13b-049-bs",f1);
myhash.Add("13b-034-bs", f1);
myhash.Add("13b-038-bs", f1);

foreach (Friend item in myhash)
{
    Console.WriteLine("Key {0}\tName {1}\tAge {2}",item.Name,item.Age,myhash.Keys);
}

I got this error:

An unhandled exception of type 'System.InvalidCastException' occurred in HashTableDemo.exe

1
  • 1
    Why are you using the non-typed Hashtable? It would be easier to use a strongly typed Dictionary<string,Friend> - that way you do not have to cast your keys or values. Iterating over it works as well - you'll get stronlgy typed KeyValuePair<string,Friend> via foreach (var kvp in yourDict) that you then can access by kvp.Key and kvp.Value without casting... Commented Dec 5, 2017 at 8:43

3 Answers 3

1

try out , as data store in hash tbale is not type of Friend object youare getting error, if you dont know type than make use of var that will resolve error

  foreach (var  item in myhash)
        {
           string key = de.Key.ToString();
           Friend val  = (Friend) item.Value;
           Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, val.Name, val.Age );
        }

or you can do like this

foreach(DictionaryEntry de in myHashtable)
{
      string key = de.Key.ToString();
   Friend val  = (Friend) de.Value;
   Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, val.Name, val.Age );
}

Read out : Hashtable Class

Sign up to request clarification or add additional context in comments.

7 Comments

@Rafalon - why its not good practice ...that is leagal way as per language structure ....it introduced with linq for that purpose only ...any ways i updated my answer with DictionaryEntry , hope you like to revert you -1 point
@KonstantinChernov - updated that part also ..............i havent seen that ..thanks for pointing it out
@Rafalon - it debated many time and using or not using it , is on developer , that what my point , in my coding style i use var ..........why not to use lagnaguge is providing that feature ...i am not adding min there
Error 1 'object' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) E:\C sharp\UnderstandingCollection\HashTableDemo\Program.cs 26 35 HashTableDemo
Please wait for 5 min to edit, I'm trying to edit your question for 5 min now, but you canceled it 4 times xD I made some language and code format improvements :)
|
0

The iterator (enumerator) of Hashtable returns objects of type DictionaryEntry. Therefore, in your foreach loop, each item will have two properties: Key and Value, both of type object. You can individually cast the Key and Value properties on each item to your desired type. For example:

foreach (DictionaryEntry item in myhash)
{
    // Cast item.Key to string
    string key = (string)item.Key;

    // And cast item.Value to Friend
    Friend friend = (Friend)item.Value;

    Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, friend.Name, friend.Age);
}

Comments

0

Use strongly typed Dictionary (using System.Collections.Generic needed):

using System.Collections.Generic;

public class Program
{
    class Friend
    {
        public string Name {get;set;}    
        public int Age {get;set;}

        public Friend(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

    public static void Main()
    {
        // this is my class object
        Friend f1 = new Friend("Nazir", 24);
        Friend f2 = new Friend("Hamza", 24);
        Friend f3 = new Friend("Abdullah", 23);
        var myDict = new Dictionary<string, Friend>();
        // add this object in hashtable object
        myDict["13b-049-bs"] = f1;
        myDict["13b-034-bs"] = f1;
        myDict["13b-038-bs"] = f1;
        foreach (KeyValuePair<string, Friend> item in myDict)
        {
            Console.WriteLine("Key {0}\tName {1}\tAge {2}", item.Key, item.Value.Name, item.Value.Age);
        }
    }
}

Strongly typed has the advantage that you never will put an Enemy (or some other Type inside this dict - unless it derives from Friend.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.