thecrusader
thecrusader

Reputation: 311

How to retrieve data from hashtable when value is given as an object

hi I want to enter three values into hash table so I entered one value as key and other two converted them into object and passed as value`

class UsingHashTable
{
    public int empId;
    public String empName { get; private set; }
    public decimal salary { get; private set; }

    public UsingHashTable(string empName, decimal salary)
    {
        this.empName = empName;
        this.salary = salary;
    }

    Hashtable employeeHash = new Hashtable();

    UsingHashTable emp;

    Console.WriteLine("Enter Employee ID ");
    empId = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Enter Employee Name ");
    empName = Console.ReadLine();

    Console.WriteLine("Enter Salary of the employee ");
    salary = Convert.ToDecimal(Console.ReadLine());

    emp = new  UsingHashTable(empName,salary);

    employeeHash.Add(empId, emp);
}

Now the actual problem comes! How to retrieve the values from the hashtable where key is coming but from value I need to retrieve two values how??

foreach(DictionaryEntry temp in employeeHash) 
{
    Console.WriteLine(temp.Key + " " + temp.Value.eName + " " + temp.Value.salary);
}

I am exactly getting the error at temp.Value.eName and temp.Value.salary

Upvotes: 0

Views: 1464

Answers (3)

mehrdad safa
mehrdad safa

Reputation: 1071

It is because late binding not supported in C# by default. it means C# Identifies the temp.Value as Object not UsingHashTable. and object class does not have Name property.
to resolve this simply cast temp.Value to UsingHashTable.
example:
var temp2=(UsingHashTable)temp.Value;
Console.WriteLine(temp2.Name);

Upvotes: 0

Cyprien Autexier
Cyprien Autexier

Reputation: 1998

You need to cast temp.Value to your type

Console.WriteLine(temp.Key + " " + ((UsingHashTable)temp.Value).eName + " " + ((UsingHashTable)temp.Value).salary);

But I would definitely recommend using Dictionnary<TKey,TValue> which will avoid the need to cast.

var employeeHash = new Dictionary<int,UsingHashTable>
var emp = new  UsingHashTable(empName,salary);
employeeHash.Add(empId, emp); 

And your loop will work just fine

 foreach(var temp in employeeHash) 
 {
     Console.WriteLine(temp.Key + " " + temp.Value.eName + " " + temp.Value.salary);
 }

Upvotes: 4

fhnaseer
fhnaseer

Reputation: 7277

Hashtable.Key and Hashtable.Key are of object types. You need to cast these to your desired objects (UsingHashTable in your case) and then retrieve its properties (empName, empId)

foreach (DictionaryEntry temp in employeeHash)
{
    int id = (int) temp.Key;
    UsingHashTable employee = (UsingHashTable) temp.Value;
    Console.WriteLine(id + " " + employee.eName + " " + employee.salary);
}

Its better to use Dictionarty() here,

Upvotes: 0

Related Questions