So I found out today that structs and classes act differently when used to assign to variables in C#.. It's to my understanding that when I assign a struct to a variable, the variable stores a copy of that struct, and when I assign a class to a variable, the variable stores the reference to that class instance.
In this case, dad2 contains a copy of dad1, so shouldn't anything I do to dad2 not affect dad1? It's not the case apparently because when I add a son to dad2 it also adds the same son to dad1.
public struct Dad {
public string name;
public List <Son> sons;
public struct Son {
public string name;
public Son (string n) {
name = n;
}
}
}
static void Main (string [] args) {
Dad dad1 = new Dad ();
dad1.name = "Bob";
dad1.sons = new List <Dad.Son> {new Dad.Son ("A")};
Dad dad2 = dad1;
Debug.WriteLine (dad2.Equals (dad1) + " " + dad1.sons.Count () + " " + dad2.sons.Count ());
//true 1 1
dad2.sons.Add ( new Dad.Son ("B"));
Debug.WriteLine (dad2.Equals (dad1) + " " + dad1.sons.Count () + " " + dad2.sons.Count ());
//true 2 2
}