1

I'll try to explain what I want to do:

If I have this class:

public class MyClass
{
    public string foo { get; set; }
    public string bar { get; set; }
    public string age { get; set; }
}

And I instantiate three classes in three different objects like this:

void Main()
{
    var myA = new MyClass() { foo = "foo", bar = "bar", age = "age" };
    var myB = new MyClass() { foo = "foo", bar = "change" };
    var myC = new MyClass() { foo = "xxx", bar = "yyy", age = "zzz" };

    //I want myC with this values: foo = "xxx", bar = "change", age = "zzz"
}

So that I want that only the different not null properties from myAcomparing myB be copied to myC. Only myB.bar is a not null different property comparing myA.bar and this should be the only change copied to myC.bar

How I should I do that? Using Automapper? Or maybe using System.Reflection? Which is the easiest and best practice to do this?

EDIT I'm now using a modified version of this solution: Apply properties values from one object to another of the same type automatically?

Passing the myC object like a parameter but I'm guessing if this is the best solution

rasputino
  • 691
  • 1
  • 8
  • 24

1 Answers1

0

Based on what you've provided the simplest approach would be to add an instance method to MyClass to do the copy.

Something like:

public class MyClass
{
    public string foo { get; set; }
    public string bar { get; set; }
    public string age { get; set; }

    public MyClass DiffCopy(MyClass diff)
    {
        MyClass copy = new MyClass
        {
            foo = this.foo != diff.foo ? this.foo : null,
            bar = this.bar != diff.bar ? this.bar : null,
            age = this.age != diff.age ? this.age : null,
        };

        return copy;
    }
}
sipsorcery
  • 30,273
  • 24
  • 104
  • 155
  • The "copy" class already exists, it could be a parameter. But I think something more generic like an extension could be better – rasputino Mar 12 '20 at 11:09