-1

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.

KHRZ
  • 35
  • 5
  • Just use a private setter for `Parent` and set it in the constructor of its parent https://dotnetfiddle.net/3bzkG9 Yes it's not readonly, but it's impossible otherwise, as you can only set readonly proprties in the constructor. – Charlieface Jun 30 '23 at 00:05
  • show me the code – TimChang Jun 30 '23 at 01:17

1 Answers1

1

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.

John Wu
  • 50,556
  • 8
  • 44
  • 80