The KeyValuePair
s are structs and therefore will be recreated. However, the values of the KeyValuePair
are not recreated because that are reference types. Therefore the same instance is still referenced in both data structures.
The performant way to solve that is to implement IClonable
(or a custom clone method) and create a deep clone of your object manually. However that is time-consuming and you have to maintain the clone method if the object structure changes:
public void ListFiller()
{
newListCopy = new List<KeyValuePair<string, object>>();
foreach (var pair in newList)
{
var clone = (pair.Value as IClonable)?.Clone();
// handle case that the object does not implement IClonable
newListCopy.Add(new KeyValuePair<string, object>(pair.Key, clone );
}
}
As you already mentioned, a simpler way is, to use serialization for recreating the whole data structure. That is relativly easy to implement but not so performant (is that actually a problem?) and the objects need to be serializable.
The internet is full of similar questions and solutions.