'c# - clone array of list of objects not working [duplicate]

I'm trying to clone array of list of objects. the clone modified when the original list modified (one of the properties of Page object). how do i prevent it ?

public List<Page>[] pageStore = new List<Page>[2];
public List<Page>[] tmpPageStore = new List<Page>[2];

...

tmpPageStore = pageStore.ToArray();

I also tried use Clone() method



Solution 1:[1]

First, your variables are arrays of lists so the lists will be copied by reference, and any content then belongs to the lists, your ToArray or Clone only works one level for the base array.

So in this case, you would need to loop over the items in the array, then within that loop, loop over the items in each list.

For example (just an example and not necessarily a pretty one)

tmpPageStore = pageStore.Select(l => l?.Select(p => p.Clone()).ToList()).ToArray();

If you have a clone method for the page, otherwize that step would need to be replaced with a new or similar creation of new page objects

Solution 2:[2]

You need to clone each object inside the new list as well. Clone will only duplicate the list itself, so if the list is a list of object (references), the lists will now reference the same instances

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 David MÃ¥rtensson
Solution 2 Lee Taylor