Sas
Sas

Reputation: 2503

Cannot access a variable due to the access level protection

I have following classes:

class Department
{
 private string departmentId;
 private string departmentName;
 private Hashtable doctors = new Hashtable();//Store doctors for 
                                                //each department
public Hashtable Doctor
{
 get { return doctors; }
}
}

I have an array list that holds department objects:

private static ArrayList deptList = new ArrayList();
public ArrayList Dept
{
 get { return deptList; }
}

I am trying to get all the doctors(the Hashtable in department class) from each department:

foreach (Department department in deptList) 
        {
foreach (DictionaryEntry docDic in department.Doctor)
        {
foreach (Doctor doc in docDic.Value)//this is where I gets an error
{

if (doc.ID.Equals(docID))//find the doctor specified
{
}
}
}
}

But I can not compile the program. It gives an Error:

foreach statement cannot operate on variables of type 'object' because
'object' does not contain a public definition for 'GetEnumerator'

Upvotes: 0

Views: 340

Answers (2)

Nudier Mena
Nudier Mena

Reputation: 3274

Prefix your class with a Public access modifier

 public  class Department
{
private string departmentId;
private string departmentName;
private Hashtable doctors = new Hashtable();//Store doctors for 
                                            //each department
 public Hashtable Doctor  
{
 get { return doctors; }
  }
 }

Upvotes: 1

Attila
Attila

Reputation: 28762

You are trying to iterate through a dictionary entry's Value field treating it as if it was a collection of Doctors. The iteration for docDic should already do what you are looking for, just need to cast the appropriate field (probably Value) of the docDic DictionaryEntry.

Doctor doc = (Doctor) docDic.Value;

Better yet, you could use generics and denote the types of the dictionary key/value at declaration of the map:

private Hashtable<string, Doctor> doctors = new Hashtable<string, Doctor>();

(similar change for the Doctor field)

Then you don't need the casting above at all.

Note: I assumed you are mapping from a doctor's id (key) to the Doctor objects (value), and that the id is a string

Upvotes: 3

Related Questions