I have created this Update method
public void Update(Person updated)
{
var oldProperties = GetType().GetProperties();
var newProperties = updated.GetType().GetProperties();
for (var i = 0; i < oldProperties.Length; i++)
{
var oldval = oldProperties[i].GetValue(this, null);
var newval = newProperties[i].GetValue(updated, null);
if (oldval != newval)
oldProperties[i].SetValue(this, newval, null);
}
}
What it does is comparing two Person objects and if there is any new values. It updates the original object. This works great, but being a lazy programmer, I would like it to be more reusable.
I would like it to work like this.
Person p1 = new Person(){Name = "John"};
Person p2 = new Person(){Name = "Johnny"};
p1.Update(p2);
p1.Name => "Johnny"
Car c1 = new Car(){Brand = "Peugeot"};
Car c2 = new Car(){Brand = "BMW"};
c1.Update(c2);
c1.Brand => "BMW"
c1.Update(p1); //This should not be possible and result in an error.
I was thinking about using and Abstract Class to hold the Method and then use some Generic, but I don’t know how to make it Class specific.
or if you want to ensure the same type: