ObjectCloner icon indicating copy to clipboard operation
ObjectCloner copied to clipboard

Option: Don't clone private fields and properties

Open marcelltoth opened this issue 6 years ago • 3 comments

This issue is a followup on @IgorMamushin's feature request in #3.

As far as I understand the request is about adding an option for not cloning private fields.

marcelltoth avatar Dec 08 '19 20:12 marcelltoth

Sometimes i want get object with clone only public property and field. But some property can be set in constructor, like this:

class MyClass
{
    private Dictionary<int, string> _myPrivate

    public MyClass()
    {
        _myPrivate = new Dictionary<int, string>();
    }
}

I think you can use new clone strategy with Expression.New() and foreach on public property/field, for generate clone func. If class have no empty ctor, cloner can return Exception.

IgorMamushin avatar Dec 09 '19 07:12 IgorMamushin

The problem with this solution is that it creates a very strict requirement of having a parameterless constructor. That's certainly not worth it.

Cloud you not use the ignore attribute you proposed in #5?

marcelltoth avatar Dec 09 '19 17:12 marcelltoth

Yep. I think if you want clone only public properties/fields you need create object with constructor. It can be contract for this mode. Or do something with initialize private field from constructor.

It's not that simple. :)

IgorMamushin avatar Dec 10 '19 09:12 IgorMamushin