I have two classes with exactly same members (properties and fields) with same datatypes. I want to map the members from one to other in automated way. I know there are more
One possibility to make this (for example for the purpose of creating your own automapper or understand how it basically works) would be to use (as already suggested) Reflection. The code can look like this:
// TODO: error handling
// Test classes
public class A
{
public string Name { get; set; }
public int Count;
}
public class B
{
public string Name { get; set; }
public int Count;
}
// copy routine
public B CopyAToB(A a)
{
B b = new B();
// copy fields
var typeOfA = a.GetType();
var typeOfB = b.GetType();
foreach (var fieldOfA in typeOfA.GetFields())
{
var fieldOfB = typeOfB.GetField(fieldOfA.Name);
fieldOfB.SetValue(b, fieldOfA.GetValue(a));
}
// copy properties
foreach (var propertyOfA in typeOfA.GetProperties())
{
var propertyOfB = typeOfB.GetProperty(propertyOfA.Name);
propertyOfB.SetValue(b, propertyOfA.GetValue(a));
}
return b;
}
The function can be used like this:
var a = new A
{
Name = "a",
Count = 1
};
var b = CopyAToB(a);
Console.Out.WriteLine(string.Format("{0} - {1}", b.Name, b.Count));
The output is:
a - 1
Please note, that the usage of reflection comes with a price - it costs performance. Using reflection you can access both private and public object members. This is for example used from Visual Studio to create test accessor objects in order to access all test object members.
Please have a look at the existing automappers (see the other answers for links) and use them instead of reinventing the wheel by yourself - the existing libraries are optimized for speed, thoroughly tested and are very comfortable to use. This way you will minimize errors in your code.