I have been creating object for a project and there are some instances that I have to create a deep copy for this objects I have come up with the use of a built in function for C# which is MemberwiseClone(). The problem that bothers me is whenever there is a new class that i created , I would have to write a function like the code below for a shallow copy..Can someone please help me improve this part and give me a shallow copy that is better than the second line of code. thanks 🙂
SHALLOW COPY:
public static RoomType CreateTwin(RoomType roomType)
{
return (roomType.MemberwiseClone() as RoomType);
}
DEEP COPY:
public static T CreateDeepClone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
MemberwiseClone is not a good choice to do a Deep Copy (MSDN):
This mean if cloned object has reference type public fields or properties they would reffer to the same memory location as the original object’s fields/properties, so each change in the cloned object will be reflected in the initial object. This is not a true deep copy.
You can use BinarySerialization to create a completely independent instance of the object, see MSDN Page of the BinaryFormatter class for an serialization example.
Example and Test Harness:
Extension method to create a deep copy of a given object:
NUnit tests: