If I have two class like so:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> employees { get; set; }
}
public class Employee
{
public string Name { get; set; }
public string Job { get; set; }
public string Date { get; set; }
}
And then if I do this:
var departments = new List<Department>();
Department d = new Department
{
Id = 1,
Name = "Depart1",
};
Department d2 = new Department
{
Id = 2,
Name = "Depart2",
};
departments.Add(d);
departments.Add(d2);
How Can I add to the employees List in the Department class with a foreach loop? When I do this:
foreach(Department dmt in departments)
{
Employee worker = new Employee
{
Name = "Steve",
Job = "Cleanup",
Date = "Today",
};
dmt.employees.Add(worker );
}
I dont get any build errors but nothing is added. Any suggestions?
You aren’t instantiating the
employeesproperty. Change your class definition to this:Or, if you don’t want to use a constructor to instantiate the
employeesproperty, you will just need to ensure that you do this before you attempt to add anEmployeeobject to theList<Employee>.