Properties in your object are value types and you can use the shallow copy in such situation like that:
obj myobj2 = (obj)myobj.MemberwiseClone();
But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization
and Deserialization
techniques with the help of BinaryFormatter
class:
public static T DeepCopy<T>(T other)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Context = new StreamingContext(StreamingContextStates.Clone);
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
The purpose of setting StreamingContext
:
We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable
interface or using built-in attributes like OnDeserialized
, OnDeserializing
, OnSerializing
, OnSerialized
. In all cases StreamingContext
will be passed as an argument to the methods(and to the special constructor in case of ISerializable
interface). With setting ContextState
to Clone
, we are just giving hint to that method about the purpose of the serialization.
Additional Info: (you can also read this article from MSDN)
Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.
Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.