force-net / DeepCloner

Fast object cloner for .NET
MIT License
530 stars 73 forks source link

How to only clone the common properties? #21

Open GF-Huang opened 3 years ago

GF-Huang commented 3 years ago
abstract class Common { 
    public int P { get; set; }
}

class ChildA : Common {  
    public int Q { get; set; }
}

class ChildB : Common {
     public int W { get; set; }
}

Common a = new ChildA();
Common b = new ChildB();

a.ShallowCloneTo(b); // Only do b.P = a.P;
force-net commented 3 years ago

Currently, it forbidden in code due possible unstable behavior. I'll think about ability to enable this functionality, if I found, that it won't cause strange runtime errors due inconsistent object state.

macias commented 11 months ago

Upvoted.

Why it would cause strange runtime errors? Do I sense correctly some old/bad memories from C++ days? ;-)

Background info: my scenario is like this, I try to keep my code as KISS as possible, so for data transfer types and DB types I keep common core type. To copy data from one to other such method would do this in one call.

force-net commented 11 months ago

A first, library copies fields, not properties. It conception of library. E.g. we have such pseudo code

public int A 
{
 get 
 {
    return Database.Read("A");
 }
 set 
 {
    Database.Write("A", value);
 }

In this code we do not have real properties, but have complex logic which can cause strange behavior on copying.

Also, there are can be next situation with virtual methods which have different implementations in derived types.

pubic abstract void ValidateStructure();

public int A 
{
 get 
 {
    return _a;
 }
 set 
 {
   ValidateStructure(value);
   value = _a;
 }

As result we can receive object in acceptable state.

I understand, that for simple situations dumb decision can work without problem, but many people uses this library to copy complex objects and situation when after copying in rare cases code can fail - seem really bad. It hard to debug and understand situation.

macias commented 11 months ago

Thank you for detailed explanation, those are valid points for sure.

But also partial copy for POCO types is valid need. So just thinking aloud, until something better appear (or idea will be burried) -- when the exception is thrown for inheritance reason, this part of code does not affect current valid uses. So there could be additional step just before exception to check if the types have any custom method. If no -- it is a POCO type and it could be copied (new feature), if it has custom methods -- exception as today.