I have a tree.
class TreeNode { public TreeNode(string name, string description) { Name = name; Description = description; } string Name { get; set; } string Description { get; set; } public List<TreeNode> Children = new List<TreeNode>(); }
I would like to fill out a large one for testing purposes. I really would like to keep the material DRY.
Say for illustrative purposes, my tree has the following structure
Parent, desc
Child 1, desc1
Grandchild 1, desc1
Child 2, desc2
How would you start filling a tree in an elegant, convenient way?
I find this code quite repetitive and error prone:
var parent = new TreeNode("Parent", "desc"); var child1 = new TreeNode("Child 1", "desc1"); var child2 = new TreeNode("Child 2", "desc2"); var grandchild1 = new TreeNode("Grandchild 1", "desc1"); parent.Children.Add(child1); parent.Children.Add(child2); child1.Children.Add(grandchild1);
EDIT
I ended up making a DSL approach:
The test demo lives here .
The implementation is here .
It uses a builder and simple DSL.
source share