'list in recursive function is getting reset

Inside a recursive function I append elements to a list (IEnumerable) that I gave the function as a parameter.

Somethig like this:

public class FooObject {
   private string Name;
   private List<FooObject>? Childs;
   
   public void RecursiveFunction(IEnumerable<FooObject> excludeList) {
      if (!excludeList.Any(x => x.Name == this.Name))
         return;

      excludeList = excludeList.Append(this);

      foreach (var child in this.Childs) {
         child.RecursiveFunction(excludeList);
      }
   }
}

The problem is that for example in a depth of 3 it appended an element to the list and has no child elements so finishes and goes up to depth 2 again and there the appended element from depth 3 isn't in the list anymore.

Is this behavior intended or do I missunderstand something in the concept of function parameters and pointers?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source