Monday, July 28, 2008

Error: Cannot implicitly convert type 'Employees' to 'System.Collections.ArrayList'. An explicit conversion exists (are you missing a cast?)

Error: Cannot implicitly convert type 'Employees' to 'System.Collections.ArrayList'. An explicit conversion exists (are you missing a cast?)

What I intended to do is to add the Employee object to the WorkerList property through the set accessor. However, I have made a mistake here. The mistake was, I used a reference of Employee object as the argument to pass it to the set accessor (a special kind of method), which takes an implicit parameter called "value", and the type of this parameter (the "value") always matches the type of the field (or the property). That's why it's causing this error.

Error Code:

public class WorkHours
{
private ArrayList workerList = new ArrayList();

public ArrayList WorkerList
{
set
{
workerList.Add( value ); // what "value" really wants is a reference to a ArrayList object.
// or
workerList = value;
}
}
}

WorkHours workHours = new WorkHours();
Employee employee1 = new Employee();

workHours.WorkerList = employee1;


Correct Code:

public class WorkHours
{
private int minWorkers; // within this particular hour.
public int MinWorkers
{
get { return minWorkers; }
set { minWorkers = value; }
}

private ArrayList workerList = new ArrayList(); // within this particular hour.

public void setWorkerList(Employees employees)
{
workerList.Add(employees);
}

public ArrayList getWorkerList()
{
return this.workerList;
}
}

WorkHours workHours = new WorkHours();
workHours.setWorkerList( new Employees() );

No comments: