I am implementing a tree think of it as a folder structure so I have a class that looks like:
public class Folder
{
//Various Props like Name etc.
public IList<Folder> Children{get;}
public Folder Parent {get;}
}
Now what I want is to be able to walk up and down the tree so given a root I can find a leaf, and given a leaf I can find the root node. So each child needs a parent. Now the question is what is the best way to add a new node to the tree. I have used two solutions in the past:
I am curious what patterns people generally use, and then if anyone has any suggestions for my specific use case. I am using nHibernate to persist my tree to SQL server. I'd rather not implement a custom collection as it's a lot of code to get this to work for something which is a very small part of my application.
After looking on MSDN you could try this:
List<Folder> children;
public ReadOnlyCollection<Folder> Children
{
get { return this.children.AsReadOnly(); }
}
If your private member must be declared as an IList then we can copy that into a list and then return it. But I really don't see a problem with using a concrete implementation as a private member. Changing the implementation later won't break compatibility.
IList<Folder> children;
public ReadOnlyCollection<Folder> Children
{
get
{
return new List<Folder>(this.children).AsReadOnly();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With