I'm studying C# Classes and am trying to create a program that has a Class called Employee and derived classes of ProductionWorker, ShiftSupervisor, and TeamLeader.
I have a list box where I want to display All the employees, and within the program, there's functionality to add, edit, or remove respective people, but rather than making 3 lists like so:
List<ProductionWorkers> pWorkers = new List<ProductionWorkers>();
List<ShiftSupervisor> sSupervisors = new List<ShiftSupervisor>();
List<TeamLeader> tLeaders = new List<TeamLeader>();
I'd like to be able to have the Employee base class have or contain some sort of list of it's derived classes and their objects.
For example I'd like to be able to be able to Add and Remove derived objects to a list of Employees in some fashion, given the following example:
List<Employee> employees = new List<Employee>();
ProductionWorker _pWorker = new ProductionWorker();
_pWorker.Name = "Bob";
_pWorker.EmployeeID = 1234;
employees.Add(_pWorker));
I don't know if that's even possible or realistic to do that, but it would seem maybe there is a way from what I've read, I'm just not sure how to implement it. I'm open to better suggestions however, if someone knows of a better or proper way to get all the Employees listed into a ListBox without having to cycle through 3 different lists of the different derived classes.
For clarity, below is the Base class, then its following derived classes.
public class Employee
{
public string Name { get; set; }
public int EmployeeNumber { get; set; }
}
class ProductionWorker : Employee
{
public int ShiftNumber { get; set; }
public decimal HourlyPayRate { get; set; }
}
class TeamLeader : ProductionWorker
{
public int ReqHours { get; set; }
public int AttendedHours { get; set; }
}
class ShiftSupervisor : Employee
{
public int Salary { get; set; }
public int AnnualProductionBonus { get; set; }
}
I didn't realize until I posted my classes here that Team Leader is actually a derived class of Production Worker. I'm not sure if that changes things...
employees.Add(_pWorker);? What you're asking sounds fairly standard, but that wrappingnew ProductionWorkerdoesn't make sense.employees.Add(new ProductionWorker(_pWorker));this line is wrong since you already created an new instance a few lines above change it toemployees.Add(_pWorker);