// 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
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 typedKeyValuePair<string,Friend>viaforeach (var kvp in yourDict)that you then can access bykvp.Keyandkvp.Valuewithout casting...