Search code examples
c#c++pointerstreeref

Two Trees: one Tree's nodes contains a List of objects; the 2nd Tree's objects contains references to the first Tree's objects. Can it be done in C#?


I want to build 2 Tree structures. The first Tree will contain nodes, each with List of my Range object:

class Range {
     public DateTime Start { get; set; }
     public DateTime End { get; set; }
}

The Tree structure will look like this:

enter image description here

I then want a 2nd Tree build from the 1st Tree. It will have a similar structure, however, when changes are made to the Range object in the 2nd Tree, I want the Range objects in the first tree to also change. Effectively, I need to hold references or pointers to the Range objects in the first Tree:

Tree #2:

enter image description here

C# is my language of preference and I know you can use the ref keyword, but I wonder if C# is really the right language for this or do I need something with pointers like C++?


Solution

  • Yes you can.

    You declared Range as class (as opposed to struct), therefore you will only be handling references (as opposed to the actual values).

    For instance, your List<Range> is a collection of references to Range objects.

    Range having reference semantics means a few things in C#, for example:

    • It only compares equal to the exact same instance
    • A Range variable can hold null
    • You always pass references, and if that's not what you want, you need to clone it explicitly
    • ...

    You may like a quick refresher on reference vs. value semantics.