I have
public class MyClass1
{
public string Name;
public string Address;
}
public class MyClass2
{
public int Id;
public string Name;
public string Address;
}
var a = new MyClass1 {Name="SomeName", Address="SomeAddress" };
I dont want to do
b.Name = a.Name;
b.Address = a.Address
because I have more than 30 fields.
I want is:
MyClass2 b = a;
What you want is not possible. I would recommend you AutoMapper which allows you to define a mapping:
Mapper.CreateMap<MyClass1, MyClass2>();
and then map between instances of those two classes:
var a = new MyClass1 { Name = "SomeName", Address = "SomeAddress" };
var b = Mapper.Map<MyClass1, MyClass2>(a);
As a bonus you will be able to do the following:
IEnumerable<MyClass1> list1 = ...
IEnumerable<MyClass2> list2 = Mapper.Map<IEnumerable<MyClass1>, IEnumerable<MyClass2>>(list1);
Another possibility is to use reflection to loop through all properties of the source object and set them in the target object but why reinventing wheels when such great tools like AutoMapper exist?
Its better you use reflection as it can loop all the properties and can set the value of matching attributes
http://odetocode.com/articles/288.aspx
check how it is retrieving values from properties
PropertyInfo[] properties = type.GetProperties();
foreach(PropertyInfo property in properties)
{
}
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