Skip to content
Oliver Ehrenmüller edited this page Oct 9, 2021 · 27 revisions

Features

  • Creates copy instructions for properties with backing fields.
  • Mark a class with AddDeepCopyConstructor-Attribute to create a deep copy constructor.
  • Mark a static method with DeepCopyExtension-Attribute to create a nullable deep copy method that supports inheritance.
  • Mark an existing copy constructor with InjectDeepCopy to insert deep copy instructions before your code. Details
  • Mark a property with IgnoreDuringDeepCopy to skip this property.
  • Mark a property with DeepCopyByReference to copy by reference.
  • Collections of types IList<>, ISet<> and IDictionary<,> are supported and described here

Start with InjectDeepCopy or DeepCopyExtension

InjectDeepCopy

Add an empty constructor with single parameter of the same class type:

class MyClass {
  public MyClass() {} // default constructor might be necessary
  [InjectDeepCopy] public MyClass(MyClass source) {} // body will be generated
}

Then you can use the copy constructor as usually:

var copy = new MyClass(sourceObject);

DeepCopyExtension

To create a compileable method just return the parameter:

static class MyTypeUtils {
  [DeepCopyExtension] public static MyType DeepCopy(this MyType myType) => myType;
}

or throw an exception

static class MyTypeUtils {
  [DeepCopyExtension] public static MyType DeepCopy(this MyType myType) => throw new NotImplementedException();
}

What gets compiled

The method body will be fully replaced.

public static MyType DeepCopy(this MyType myType) {
    return myType != null ? new MyType(myType) : null;
}

and MyType will automatically receive a deep copy constructor.

Not supported

  • Fields
  • Properties without backing field
  • Properties of types missing copy constructor
  • Properties of type System.Object
  • Collection parameterized with types missing copy constructors
  • Collection parameterized with System.Object like IList<object>