Reputation: 11404
I'm trying to create an immutable dat structure which is list of tasks. I would like each task to have a reference to the list and the list will return all the tasks and have a current task property.
The problem is how to have the cyclic reference from the tasks to the list and from the list to the tasks and still have the data structure immutable?
If I create the tasks first I can't have reference to the list because it does not exist yet and if I go the other way - create the list first I will have to change it in order to add the tasks to it.
Thank you, Ido.
Upvotes: 0
Views: 174
Reputation: 606
I just did something similar for java. Don't know if c# allows you to smuggle this
out of a constructor. If so, this solution might help here.
Upvotes: 1
Reputation: 50346
You cannot create both a list and the tasks at the same time, so you have to create one before the other. At some point you start with an empty list (e.g. in the list's constructor, or somewhere else).
Given the empty list, you create your tasks: for example in the list's constructor, or a method in the list. You can pass a reference to the list to the task's constructor. Then you add the task to the list and so the list will have a reference to the task.
Upvotes: 1
Reputation: 55619
I'm pretty sure you could create the list, and in the constructor, construct the list items, while passing the list as a parameter to them.
Pseudo-code:
List constructor:
List()
{
for each item to add
add(new Item(this));
}
Item constructor:
Item(List list)
{
this.list = list;
}
This however sort of breaks modularity, since the list constructor would have to handle all the logic to create the items.
Upvotes: 2