Double linked immutable objects (C# records)

45 Views Asked by At

I want to create two-way linked objects (parent with child, where Parent.Child property refers to the parent's child, and Child.Parent refers to the child's parent).

From what I see, this would only be possible with C# records if I use reflection, to modify the first created record with a link to the second one after creating it.

Or is there a more convenient way to do this?

What I tried: Setting up the constructor calls, and observed it's not possible to pass a "parent" reference while constructing the child that will be passed into the parent's constructor.

1

There are 1 best solutions below

0
John Wu On

Use a mutable container to hold the links.

class ItemContainer<T>
{
    public T Item { get; set; }
    public ItemContainer<T> Child { get; set; }
    public ItemContainer<T> Parent { get; set; }
}

var linkedList = new List<ItemContainer<MyRecordType>>();

var item1 = new ItemContainer<MyRecordType>();
var item2 = new ItemContainer<MyRecordType>();
item1.Child = item2;
item1.Item = new MyRecordType { Initialization data 1 };
item2.Parent = item1;
item2.Item = new MyRecordType { Initialization data 2 };

linkedList.Add(item1);
linkedList.Add(item2);

var childOfItem1 = item1.Child.Item;
var parentOfItem2 = item2.Parent.Item;

If you like you can design your own linked list class to hide the details of the mutable container.