1

I have some data members for my custom Rule object. A few integers, strings, DateTimes, all of which I have handled in the "Copy constructor" that you will see below. I have replaced the actual names of the data members for privacy.

public class Rule
{
    private int someint1;
    private int someint2;
    private string string1;
    private string string2;
    private List<Rule> children;

    public Rule(Rule other)
    {
        other = (Rule)this.MemberwiseClone(); //Handles my integers and DateTimes.
        other.string1 = String.Copy(string1);
        other.string2 = String.Copy(string2);
        //Now handle List<Rule> children;-----------
    }
}

My question is since I have a List with a recursive nature being in my Rule class. (A rule may have other rules...etc.) How might I handle a deep copy of that list of children(child Rules)? Do I need to foreach loop through and recall my copy constructor if the list is not empty?

**Should not be important, but I am populating this information from Sql rather than on the fly construction.

**Edit The question flagged as a potential duplicate does not address my issue of having a List in the CustomObj class. It addresses a List in a class that isn't its own type and therefore I believe this question deserves a separate question that is not a duplicate.

Adam
  • 2,422
  • 18
  • 29
  • 2
    `Do I need to foreach loop through and recall my copy constructor if the list is not empty?` Yeah. – Matt Burland May 26 '16 at 13:58
  • Possible duplicate of [How create a new deep copy (clone) of a List?](http://stackoverflow.com/questions/14007405/how-create-a-new-deep-copy-clone-of-a-listt) – Gabriel GM May 26 '16 at 14:51
  • Except that he is called a List in a class separate from the Book class. My question regards a List within my own Rule class. – Adam May 26 '16 at 14:53

1 Answers1

0
public class Rule
{
    private int someint1;
    private int someint2;
    private string string1;
    private string string2;
    private List<Rule> children;

    public Rule()
    {

    }

    public Rule(Rule other)
    {
        other = (Rule)this.MemberwiseClone(); //Handles my integers and DateTimes.
        other.string1 = String.Copy(string1);
        other.string2 = String.Copy(string2);
        other.children = children.Select(x => x.clone()).ToList();

    }
    public Rule clone()
    {
        Rule clone = new Rule();

        clone.children = this.children;

        return clone;

    }
}
Amit Pore
  • 127
  • 3
  • 13