Not long ago I got familiar with with operator. Based on MSDN, when using the "with expression", reference types will be copied, but that logic can be changed by overriding copy constructor.
In the case of a reference-type member, only the reference to a member instance is copied when an operand is copied. Both the copy and original operand have access to the same reference-type instance. If you need to customize the record copy semantics, explicitly declare a copy constructor with the desired behavior.
This is how copy logic can be changed:
record WithOperatorTest()
{
private int _myPrivateField;
public int MyProperty { get; set; }
public List<int> MyReferenceTypeProperty { get; set; }
protected WithOperatorTest(WithOperatorTest original)
{
_myPrivateField = original._myPrivateField;
MyPublicField = original.MyPublicField;
MyProperty = original.MyProperty;
// Creating new reference
MyReferenceTypeProperty = new List<int>(original.MyReferenceTypeProperty);
}
}
I wonder if it's somehow possible to use "with" operator inside a copy constructor to not write unnecessary code & use benefits of the operator to override only the logic that needs to be overridden? I'd love to achieve a behavior like this:
protected WithOperatorTest(WithOperatorTest original)
{
return original with { MyReferenceTypeProperty = new List<int>(original.MyReferenceTypeProperty) };
}
Or:
protected WithOperatorTest(WithOperatorTest original)
{
this = original with { MyReferenceTypeProperty = new List<int>(original.MyReferenceTypeProperty) };
}
Or:
protected WithOperatorTest(WithOperatorTest original) with
{
MyReferenceTypeProperty = new List<int>(original.MyReferenceTypeProperty);
}
All the attempts above, of course, do not compile. My question is whether the is currently a way to achieve the desired behavior or we need to write copy constructors in "the old way"?