I am trying to create a shallow copy (new instance) of an object, without manually setting each field. This object is not a type I have the ability to modify, so I cannot go into the object and implement ICloneable ... I am a bit stuck. Is there an easy way to simply clone an object, or will I have to implement some Clone() method that simply copies each field into a new object?
Thanks in advance for any help!
ICloneable interface) should contain public or protected copy constructor. Base class should declare Clone method as virtual. Derived class should contain copy constructor which calls base class's copy constructor. Both base and derived class should implement Clone method by simply invoking the copy constructor.
The ICloneable interface enables you to provide a customized implementation that creates a copy of an existing object. The ICloneable interface contains one member, the Clone method, which is intended to provide cloning support beyond that supplied by Object.
clone - create something new based on something that exists. copying - copy from something that exists to something else (that also already exists).
Use reflection to look at the fields on the object and use that to populate the new instance.
This makes some assumptions about the existence of a constructor that takes no arguments.
Type t = typeof(typeToClone);
var fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var copy = Activator.CreateInstance(t);
for(int i = 0; i < fields.Length; i++)
fields[i].SetValue(copy, fields[i].GetValue(existing));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With