I have a translation method, which takes in a class, and 'upgrades' it to a new type. For example:
class Animal {
public int LegCount {get; set;}
public string Name {get; set;}
}
class FarmAnimal: Animal {
public string Benefit {get; set;}
}
// I get passed the Animal type
var a = new Animal();
a.LegCount = 4;
a.Name = "Cow"
// And I need to upgrade it to a Farm Animal
var b = new FarmAnimal();
b.LegCount = a.LegCount;
b.Name = a.Name;
b.Benefit = "Milk";
But if a developer adds a new field to Animal, say EyeCount, they will forget to add the tranlation to the upgrade method.
What I would prefer to do is itterate through the properties of the Animal class, and copy them to the new FarmAnimal class (And then add the extra fields via my own logic). I just need the sub class fields copied.
I was hoping I could so domething like:
var props = typeof(Animal).GetProperties();
FarmAnimal target = new FarmAnimal ();
foreach (var prop in props)
{
....
}
target.Benefit = "Milk"; // So, I add the extra fields after translating the sub class fields.
But I am not sure how to do the actual translation. How can I copy each property across within the ForEach. Or is there a better way to achieve this?
Edit: This is very close, I think, but I need to excluse fields that do not have a Set.
var props = typeof(Animal).GetProperties();
FarmAnimal fa = new FarmAnimal();
foreach (var prop in props)
{
typeof(FarmAnimal )
.GetProperty(prop.Name,
BindingFlags.IgnoreCase |
BindingFlags.Instance |
BindingFlags.Public | BindingFlags.SetField)
.SetValue(fa,
prop.GetValue(animal));
}
But I have a few proprties with no Set.
Edit: May have found it.
GetProperties().Where(prop => prop.GetSetMethod() != null)