Suppose you have 2 classes like so:
public class ClassA {
public int X { get; set; }
public int Y { get; set; }
public int Other { get; set; }
}
public class ClassB {
public int X { get; set; }
public int Y { get; set; }
public int Nope { get; set; }
}
Now imagine you have an instance of each class and you want to copy the values from a into b. Is there something like MemberwiseClone that would copy the values where the property names match (and of course is fault tolerant — one has a get, and the other a set, etc.)?
var a = new ClassA(); var b = new classB();
a.CopyTo(b); // ??
Something like this is pretty easy in a language like JavaScript.
I’m guessing the answer is no, but maybe there is a simple alternative too. I have written a reflection library to do this, but if built in to C#/.NET at a lower level would probably be more efficient (and why re-invent the wheel).
There’s nothing in the framework for object-object mapping but there’s a very popular library out there that does this: AutoMapper.
By the way, just for learning, here’s a simple way you can implement what you want. I haven’t tested it thoroughly, and it’s nowhere as robust / flexible / performant as AutoMapper, but hopefully there’s something to get out of the general idea: