Cloning objects in C #

I defined the following 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 tries to clone objects of this derived class. How to implement a deep copy in a base class?

+4
c # deep-copy
Apr 6 2018-10-06T00:
source share
2 answers

If your types are serializable , you can 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); } } 
+7
Apr 6 2018-10-06T00:
source share

The best way is usually to serialize the instance and re-commit it as a new instance. One way to do this is described here .

My only caveat in this article is that do not implement it as ICloneable - this interface is deprecated and confuses callers of your class. It would be best to move this implementation to the utility method and name it there.

0
Apr 6 '10 at 14:40
source share



All Articles