What you can do is pass around a Dictionary
of items mapped to their clones. Now the method will look like this:
static private T DeepClone<T> (this T instance, IDictionary<object, object> originalToAlreadyCloned) where T: class
Now the first thing you do after if (instance == null) return null;
, is check if instance
is present in originalToAlreadyCloned
and if so, return it.
In order to populate it, after
copy = (T) formatter.Deserialize(stream);
copy = CreateInstance<T>(type);
call originalToAlreadyCloned.Add(instance, copy);
Finally, provide a new top-level method:
static private T DeepClone<T> (this T instance) where T: class
that simply calls DeepClone(instance, new Dictionary<object, object>());
By the way, value = value != null && value.GetType().IsClass? value.DeepClone() : null;
seems wrong. What you're saying is, if value
is not a class, set it to null. But if it's not a class, you can't generally set it to null. I'm not sure why you don't just clone these items too, and why DeepClone
is restricted to only classes.