Search code examples
c#deep-copycloning

Cloning objects in C#


I defined next class with virtual properties:

public class Order: BaseEPharmObject
{
    public Order()
    {
    }

    public virtual Guid Id { get; set; }
    public virtual DateTime Created { get; set; }
    public virtual DateTime? Closed { get; set; }
    public virtual OrderResult OrderResult { get; set; }
    public virtual decimal Balance { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual Shift Shift { get; set; }
    public virtual Order LinkedOrder { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual decimal TotalPayable { get; set; }

    public virtual IList<Transaction> Transactions { get; set; }
    public virtual IList<Payment> Payments { get; set; }
}

and trying to clone objects of that derived class. How to implement a deep copy right in the base class?


Solution

  • If your types are serializable you could use BinaryFormatter:

    public static T DeepClone<T>(T obj)
    {
        using (var stream = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, obj);
            stream.Position = 0;
            return (T)formatter.Deserialize(stream);
        }
    }