Re: OOP object collections
- From: "schneider" <eschneider.news.ms@xxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 7 Feb 2008 09:35:18 -0600
Also note, for public APIs it is recommended that you use the
System.Collections.ObjectModel namespace and not List<>.
Schneider
"RSH" <way_beyond_oops@xxxxxxxxx> wrote in message
news:ebNPNAZaIHA.4284@xxxxxxxxxxxxxxxxxxxxxxx
Hi,
I have a basic question around how to handle collections of objects when
using object composition.
In my sample below I have a typical arrangement, I have a Company class
and a Employee class. My question is whether I should create a collection
IN the company class to store the employees, or as in my sample below,
create a EmployeeCollection class which is responsible for managing the
collection of employees?
It seems like it is a better construct to have a seperate class to manage
the collection...am I wrong there?
Thanks,
Ron
public class Company
{
private int m_Id;
private string m_Name;
private EmployeeCollection m_EmployeeCollection = null;
public Company(int Id, string Name)
{
m_Id = Id;
m_Name = Name;
LoadEmployees();
}
public int Id { get { return m_Id;}}
public string Name { get { return m_Name; } set { m_Name = value; } }
protected void LoadEmployees()
{
Employee employee = null;
m_EmployeeCollection = new EmployeeCollection(this);
// Load employees from datasource into EmployeeCollection object
employee = new Employee(this, 0, "Smith", "Doug");
m_EmployeeCollection.Add(employee);
}
}
public class EmployeeCollection
{
private List<Employee> m_EmployeeList = new List<Employee>();
private Company m_Parent = null;
public EmployeeCollection(Company Parent)
{
m_Parent = Parent;
}
public IEnumerable<Employee> GetEmployees()
{
foreach (Employee employee in m_EmployeeList)
{
yield return employee;
}
}
public void Add(Employee employee)
{
m_EmployeeList.Add(employee);
}
public void Remove(int Id)
{
foreach (Employee employee in m_EmployeeList)
{
if (employee.Id == Id)
{
m_EmployeeList.Remove(employee);
}
}
}
}
public class Employee
{
private int m_Id;
private string m_LastName;
private string m_FirstName;
private Company m_Parent = null;
public Employee(Company Parent,int Id, string LastName, string FirstName)
{
m_Id = Id;
m_LastName = LastName;
m_FirstName = FirstName;
m_Parent = Parent;
}
public int Id { get { return m_Id;}}
public string LastName { get { return m_LastName; } set { m_LastName =
value; } }
public string FirstName { get { return m_FirstName; } set { m_FirstName =
value; } }
}
.
- Follow-Ups:
- Re: OOP object collections
- From: RSH
- Re: OOP object collections
- References:
- OOP object collections
- From: RSH
- OOP object collections
- Prev by Date: Re: SendKeys RCONTROL possible?
- Next by Date: Debug Class library
- Previous by thread: Re: OOP object collections
- Next by thread: Re: OOP object collections
- Index(es):
Relevant Pages
|