Reputation: 1574
I have an object with properties for a Part. But some parts are "Parents" and have child parts. Those child parts have all the same properties as the parent part (not the same property values, just the same properties with their own values).
So for each Part object, I want to have a list property of child parts. What I want to do, is create a list of Part Objects - one for each child part within the Part object if it's a parent part.
My question is... can you have a list of objects of the same object type within an object? (does this even make sense?)
Simple example:
public class Part
{
private string _Part;
private string _Description;
private List<Part> _childParts = new List<Part>();
}
Upvotes: 3
Views: 2650
Reputation: 1396
I think you need to implement the Composite pattern: https://en.wikipedia.org/wiki/Composite_pattern
Upvotes: 3
Reputation: 31087
Yes, you can, it's the cornerstone of all tree structures.
For instance:
class Part {
public List<Part> Children { get; set; }
public Part Parent { get; set; }
}
is perfectly valid.
Upvotes: 5