I have got two user defined CLR objects which are identical and only differ in name, for example this code:
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string LastName { get; set; }
public string ETC { get; set; }
}
public class PersonData
{
public string Name { get; set; }
public string Address { get; set; }
public string LastName { get; set; }
public string ETC { get; set; }
}
I know that this can be done by creating an object from either of these CLR's and than pass all properties one by one to it.
But is there another way? I got a few CLR's that are pretty big, 15+ properties.
[Edit]
Some more context. The classes where already there. I generated a model from the database using EntityFramework
. The database has almost the exact same structure as the classes.
Also, it's a lot of code that was already there. These classes also inherit from several interfaces etc. Refactoring now is not an option, so i'm looking for an easy fix for now.
Assumming you don't want both classes to inherit from an interface you can try Automapper it's a library for automatically mapping similar classes.
If you are the author of those classes, you could have them implement the same interface, or even better, inherit from the same class. That way you don't have to copy values from one to another - just use a reference to their parent type. Remember, having couples of unrelated types which have exactly the same members is a sure sign that you need to rethink your design ASAP.
And, just for the sake of completeness, here's what it looks like with reflection:
var a = new Person( ) { LastName = "lastn", Name = "name", Address = "addr", ETC = "etc" };
var b = new PersonData( );
var infoPerson = typeof( PersonData ).GetProperties( );
foreach ( PropertyInfo pi in typeof( Person ).GetProperties( ) ) {
object value = pi.GetValue( a, null );
infoPerson.Single( p => p.Name == pi.Name )
.SetValue( b, value, null );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With