Both your custom class, NewClass
, and List<T>
are reference types.
From Microsoft's documentation on Reference Types:
There are two kinds of types in C#: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable. With value types, each variable has its own copy of the data, and it is not possible for operations on one variable to affect the other (except in the case of in, ref and out parameter variables; see in, ref and out parameter modifier).
[emphasis mine]
So, to accomplish what you want all you'd have to do is assign each child's NewClassList
property to its parent's NewClassList
.
var firstParent = new ParentClass
{
NewClassList = new List<NewClass>(),
ChildClassList = new List<ChildClass>()
};
firstParent.ChildClassList.Add(new ChildClass
{
NewClassList = firstParent.NewClassList
});
firstParent.ChildClassList.Add(new ChildClass
{
NewClassList = firstParent.NewClassList
});
firstParent.NewClassList.Add(new NewClass
{
Name = "Hugh Mann",
Age = 48
});
//firstParent and both children now contain Hugh Mann.
firstParent.ChildClassList[0].NewClassList.Add(new NewClass
{
Name = "Sillius Soddus",
Age = 43
});
//firstParent and both children now contain Sillius Soddus.
firstParent.ChildClassList[1].NewClassList.Add(new NewClass
{
Name = "Joanna Dance",
Age = 62
});
//firstParent and both children now contain Joanna Dance.
firstParent.NewClassList[0].Age = 23;
//Hugh Mann now has an age of 23 in firstParent and its children
If you were to assign a different list to either the parent or the child they would no longer be referencing the same list. Changes to one list would not occur on the other as they are referencing completely different lists.
var firstParent = new ParentClass
{
NewClassList = new List<NewClass>(),
ChildClassList = new List<ChildClass>()
};
firstParent.ChildClassList.Add(new ChildClass
{
NewClassList = firstParent.NewClassList
});
firstParent.ChildClassList[0].NewClassList.Add(new NewClass
{
Name = "Sillius Soddus",
Age = 43
});
//firstParent and its child now contain Sillius Soddus.
firstParent.NewClassList = new List<NewClass>
{
new NewClass
{
Name = "Hugh Mann",
Age = 22
}
};
//firstParent.NewClassList now references a totally different list. It contains Hugh Mann, while firstParent.ChildClassList[0] contains Sillius Soddus.
firstParent.NewClassList.Add(new NewClass
{
Name = "Ian D. Dark",
Age = 33
});
//firstParent.NewClassList now contains Hugh Mann and Ian D. Dark. Since firstParent.ChildClassList[0] references a totally different list it still only contains Sillius Soddus.