Passing values ​​between two classes by casting

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 do not want to do

b.Name = a.Name;
b.Address = a.Address 

because I have more than 30 fields.

I want to:

MyClass2 b = a;
+3
source share
4 answers

What you want is impossible. I would recommend you AutoMapper , which allows you to define a mapping:

Mapper.CreateMap<MyClass1, MyClass2>();

and then map between instances of these two classes:

var a = new MyClass1 { Name = "SomeName", Address = "SomeAddress" };
var b = Mapper.Map<MyClass1, MyClass2>(a);

As a bonus, you can do the following:

IEnumerable<MyClass1> list1 = ...
IEnumerable<MyClass2> list2 = Mapper.Map<IEnumerable<MyClass1>, IEnumerable<MyClass2>>(list1);

Another possibility is to use reflection to scroll through all the properties of the source object and set them in the target object, but why reinvent the wheels when there are such large tools as AutoMapper?

+5
source

,

http://odetocode.com/articles/288.aspx

,

 PropertyInfo[] properties = type.GetProperties();

 foreach(PropertyInfo property in properties)
 {
 }
+1

As an alternative solution, you can create a constructor in MyClass2 that takes an instance of MyClass1 and sets all the properties.

public class MyClass2
{
    public int Id; 
    public string Name;
    public string Address;

    public MyClass2(MyClass1 a)
    {
        this.Name = a.Name;
        this.Address = a.Address;
    }
}

Then you could do it

MyClass2 b = new MyClass2(a);
+1
source

The simplest thing is to simply have a method called updateFromClass1 (MyClass1) in MyClass2

You can also use Reflection. Use http://msdn.microsoft.com/en-us/library/ch9714z3.aspx to get all fields from a type. FieldInfo receives and sets methods for updating the value.

0
source

All Articles