Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing values between 2 classes by casting

Tags:

c#

.net

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;
like image 895
killebytes Avatar asked Jul 16 '26 06:07

killebytes


2 Answers

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?

like image 167
Darin Dimitrov Avatar answered Jul 18 '26 18:07

Darin Dimitrov


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)
 {
 }
like image 37
Deepesh Avatar answered Jul 18 '26 20:07

Deepesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!