Question Allowing a child object to know its parent

cadwalli

Active member
Joined
May 27, 2010
Messages
41
Location
United Kingdom
Programming Experience
10+
Hi

Can someone help please.

I have created a class called "Department", and a collection called DepartmentCollection.

The class is (basically):

property DepartmentCode as string
property DeprtmentDescription as string
property Subdepartments as DepartmentCollection

This will allow a department to contain many subdepartments

However, if i want the subdepartment objects to contain a reference back to the part Department, how would I do this?

I.e. If i have the department structure:

Finance (Department Object)
-> Subdepartment Account payable
-> Subepartment Accounts Receivable

Then the "parent" object "Finance" will have two department objects in its subdepartment collection for Accounts Payable and Accounts Receivable.

Now, if im looking at the Accounts Payable object, how can I easily tell which Parent obejct (in this case finance) this object belogs to.

Would I create another property in the department class called "parent" for example, and store in that the object of the parent on child creation?

In this example its pretty simple to determine which the parent is, but if I was creating a detailed BOM then it would not be so easy.

My concern is that if i pass the object in to the child it creates heavy memory use, or is there just a way of passing a reference to it so that I can go back "up" the object tree if I needed to.

Hope this makes sense.

Thanks in advance for any help.

Ian
 
You have to provide a constructor with a Department argument:

VB.NET:
Property ParentDepartment As Department
Sub New(desc as String, parent as Department)
Me.DepartmentDescriotion = desc
Me.ParentDepartment = parent
End Sub


..

Dim finance as New Department("finance", Nothing)
finance.Subdepartments.Add(New Department("accounts payable", finance))
finance.Subdepartments.Add(New Department("accounts receivable", finance))

A reference to the parent is necessary: there's no good way to determine in .net "what other objects hold a reference to this object" without using reflection (generally not advisable in a production system)
Just create the links yourself.. In terms of memory use, we're talking about a couple of bytes necessary to hold a memory address number - unless youre creating billions of departments, having this extra reference is going to swell your program's memory use by some number of bytes or kilobytes, not even megabytes
 
Back
Top