Weird Data Tree behavior within a C# component - SOLVED

I came across a weird behavior while I was trying to make a simple C# scripted component to append data on a new branch at the end of an input data tree (supposing, for an initial simplified case, that the tree structure had just one level so the branch indices are {0}, {1}, … {n}). I’ve tried to append data with 2 methods. One works as expected, while the other acted funny: when I tested it with a ‘Series’ component, the index of its last branch (the INPUT one) increases by one each time I re-plug it in the C# one.
This looks weird to me, I tried with new Series components, copy-pasting the C# into a new definition and it still messes with the Data Tree index of the input component. I am uploading it here in case this might expose a potential bug that needs fixing. I’m using Rhino 6, latest SR as of today.
See the screenshot (and the attached gh file) below.

Weird tree (10.0 KB)

I guess the problem is the first line (which btw does not correspond to what is copypasted in the panel above and shown in the screenshot).

DataTree<object> D1 = new DataTree<object>(Dt);

This creates a shallow copy, I think for your code to work as expected you need to create a deep copy of the tree?

Sorry, the panel/component code mismatch is my fault, I did try to make a shallow copy after and forgot to change it back in the definition I uploaded, but that’s not the cause of the behavior.

In fact, if you copy/paste the code in the panel in the C# component it still acts weird as described before. In this case T will only output a list with the new branch index but the last branch index of the input series is incremented.

Looking at the code once more though, it seems that the cause is indeed a reference problem: in order to generate the new path I am creating a lastBranch variable that references the last element of Dt.Paths, then I am incrementing all the non-zero values by 1 (yes, not very robust as a strategy, but I needed to start from the simplest case). This increment in the values of lastBranch has evidently consequences on the path indices of the input DataTree.

Ok, I got it sorted out. It was indeed the fact that I was referencing the input Data Tree Branch Path structure and, essentially, it inherited the changes I was making in the component. By changing the code inside the C# as follows the weird behavior disappeared:

DataTree<object> D1 = new DataTree<object>();
GH_Path lastBranch = Dt.Paths[Dt.BranchCount - 1];

int[] lBi = new int[lastBranch.Indices.Count()];

for (int j = 0; j < lBi.Length; j++){
  if (lastBranch.Indices[j] > 0) lBi[j] = lastBranch.Indices[j] + 1;
  else lBi[j] = 0;

GH_Path newBranch = new GH_Path(lBi);
D1.AddRange(i, newBranch);

T = D1;