Skip to content

Constructors

Oliver Ehrenmüller edited this page Oct 9, 2021 · 12 revisions
  • Value types are copied by assignment
  • Reference types must provide a copy constructor (by itself or generated by DeepCopy.Fody) or a valid DeepCopyExtension-method
  • IList<>, ISet<> and IDictionary<,> are supported and described here

Your code

public class SomeObject
{
    public int Integer { get; set; }
    public SomeEnum Enum { get; set; }
    public DateTime DateTime { get; set; }
    public string String { get; set; }
    public OtherObject Object { get; set; }
}

What gets compiled

public class SomeObject {
  public SomeObject() {}
  public SomeObject(SomeObject obj)
  {
    this.Integer = obj.Integer;
    this.Enum = obj.Enum;
    this.DateTime = obj.DateTime;
    this.String = obj.String != null ? new string(obj.String.ToCharArray()) : (string) null;
    this.Object = obj.Object != null ? new OtherObject(obj.Object) : (SomeObject) null;
  }
  // properties
}

OtherObject requires a constructor with Signature OtherObject(ObjectObject source). This constructor can be

  • implemented manually
  • empty and marked with [InjectDeepCopyConstructor] to let DeepCopy generate the code
  • generated by DeepCopy with the class marked with [AddDeepCopyConstructor] or
  • generated by DeepCopy with an extension method marked with [DeepCopyExtension]

Custom implementation

You can mix a deep copy constructor with your own code. InjectDeepCopy does not replace the constructor body. Instead the deep copy code is injected between base constructor call and first instruction of the constructor body:

Your code

public class MyObject
{
  public class MyObject() {}

  [InjectDeepCopy]
  public class MyObject(MyObject source)
  {
    SecondObject = CustomMethod(source.SecondObject);
  }

  public OtherObject FirstObject { get; set; }
  [IgnoreDuringDeepCopy] public SpecialObject SecondObject { get; set; }
  public OtherObject ThirdObject { get; set; }
}

What gets compiled

public class MyObject
{
  public class MyObject() {}

  public class MyObject(MyObject source)
  {
    FirstObject = source.FirstObject != null ? new OtherObject(source.FirstObject) : null;
    ThirdObject = source.ThirdObject != null ? new OtherObject(source.ThirdObject) : null;
    SecondObject = CustomMethod(source.SecondObject);
  }

  public OtherObject FirstObject { get; set; }
  public SpecialObject SecondObject { get; set; }
  public OtherObject ThirdObject { get; set; }
}
Clone this wiki locally