471,326 Members | 2,649 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,326 software developers and data experts.

Collections and Parent Reference


I have a class, Folder, that I want to hold a reference to its parent
Folder as well as its subfolders.

I'm using List<Folder> to hold its list of sub folders. What I want to
do is when a folder is added to this list, automatically set the parent
reference.

But this seems impossible. It seems like I need to keep List<Folder>
private and expose an "AddFolder" method that adds the folder to the
list, and then also sets the folder's parent reference.
Something like this:

class Folder
{
private List<Folder> _subFolders;

public void AddFolder(Folder f)
{
_subFolders.Add(f);
f.Parent = this;
}
}

Feb 8 '06 #1
1 1538
Hi Brian,
the code you have shown is a good example of encapsulation which is a good
concept to model in your code. You have hidden the underlying datatype from
the user and encapsulated your processing. If you expose your data to the
user directly then they may perform undesirable actions upon it. Ideally
keep your data type encapsulated inside the class and provide these accessor
methods when possible.

Mark.

"Brian P" wrote:

I have a class, Folder, that I want to hold a reference to its parent
Folder as well as its subfolders.

I'm using List<Folder> to hold its list of sub folders. What I want to
do is when a folder is added to this list, automatically set the parent
reference.

But this seems impossible. It seems like I need to keep List<Folder>
private and expose an "AddFolder" method that adds the folder to the
list, and then also sets the folder's parent reference.
Something like this:

class Folder
{
private List<Folder> _subFolders;

public void AddFolder(Folder f)
{
_subFolders.Add(f);
f.Parent = this;
}
}


Feb 8 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.