C# Objects - What do objects know?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Do objects what referances them?

Example -

Adding an employee object to an organization object. If the organization
keeps all of its employees in an array list, do the employees know what
organization they belong to?
 
No, unless you add an attribute and pass a parameter to a constructor of
your employee object for example:

class Employee {
private string ParentOrganization = "";

public Employee(string Owner) {
ParentOrganization = Owner;
}
}

somewhere in organization ...

Employee e1 = new Employee("Department of Transportation");
list.Items.Add(e1);

and set that from the organization object.
 
BolineC,

No, they do not. If you want to implement this, then the organization
object will have to inform the employee object that particular instance is
the owner (but that doesn't mean that something can't have more than one
reference to it).

Hope this helps.
 
No. Typically the way you manage a relationship like this in an
object-oriented world is that the Organization has an AddEmployee
method or something like that. AddEmployee is then responsible for:

1. Removing the employee from whatever organization they currently
belong to.
2. Informing the employee that it now belongs to a new organization.
3. Adding the employee to the organization's employee collection.

The employee must have a property that indicates to which
organization(s) it belongs. (If it can belong to more than one then
obviously step 1 above isn't necessary.)

In short, you have to manage this relationship in your application
code, but you should manage it in one place, in a few methods, so that
you can guarantee that it is always properly maintained.
 
Back
Top