I am trying to implement a deep clone feature and already asked some question:
- IsPrimitive doesn't include nullable primitive values
- Array, List, IEnumerable, CustomList class cast to one and iterate threw them
- https://stackoverflow.com/questions/20978951
I am modifing the following code: https://stackoverflow.com/a/11308879/2598770
And currently I am facing the problem, that my original list also gets modified with "copied" objects instead of only the clone object, as recommended by the 2nd earlier question (Array, List, IEnumerable, CustomList class cast to one and iterate threw them). I have change the following code:
//Code directly from source
var cloneObject = CloneMethod.Invoke(originalObject, null);
if (typeToReflect.IsArray)
{
var arrayType = typeToReflect.GetElementType();
if (IsPrimitive(arrayType) == false)
{
Array clonedArray = (Array)cloneObject;
clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));
}
}
To a version that also handles, IList and not just arrays:
var cloneObject = CloneMethod.Invoke(originalObject, null);
if (cloneObject is IList)
{
if (typeToReflect.GetGenericArguments().Any())
{
var arrayType = typeToReflect.GenericTypeArguments[0];
if (IsPrimitive(arrayType) == false)
{
var clonedArray = (IList)cloneObject;
if (clonedArray.IsReadOnly == false)
for (var i = 0; i < clonedArray.Count; i++)
{
var originalListEntry = clonedArray[i];
var clonedListEntry = InternalCopy(originalListEntry, visited);
clonedArray[i] = clonedListEntry;
}
}
}
}
but on the line clonedArray[i] = clonedListEntry;
, it doesnt just change the clonedArray but also the originalObject
.
How can I prevent this, so that the clonedListEntry only gets set on the clonedArray?