I want to make a deep copy of an object so I could change the the new copy and still have the option to cancel my changes and get back the original object.
My problem here is that the object can be of any type, even from an unknown assembly.
I can not use BinaryFormatter
or XmlSerializer
, because the object unnecessarily have [Serializable] attribute.
I have tried to do this using the Object.MemberwiseClone()
method:
public object DeepCopy(object obj)
{
var memberwiseClone = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
var newCopy = memberwiseClone.Invoke(obj, new object[0]);
foreach (var field in newCopy.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (!field.FieldType.IsPrimitive && field.FieldType != typeof(string))
{
var fieldCopy = DeepCopy(field.GetValue(newCopy));
field.SetValue(newCopy, fieldCopy);
}
}
return newCopy;
}
The problem in this is that it's not working on an enumerable (array, list etc.), an not on dictionary.
So, how can I make a deep copy of an unknown object in C#?
TNX a lot!
It is completely impossible to deep-copy an arbitrary object.
For example, how would you handle a Control
or a FileStream
or an HttpWebResponse
?
Your code cannot know how the object works and what its fields are supposed to contain.
Do not do this.
It's a recipe for disaster.