Without using AutoMapper... (because someone in charge of this project will shit bricks when they see dependencies)
I have a class (class A) with however many properties. I have another class (class B) with those same properties (same names and type). Class B could also have other un related variables.
Is there some simple reflection code that can copy values from class A to class B?
The simpler the better.
Type typeB = b.GetType();
foreach (PropertyInfo property in a.GetType().GetProperties())
{
if (!property.CanRead || (property.GetIndexParameters().Length > 0))
continue;
PropertyInfo other = typeB.GetProperty(property.Name);
if ((other != null) && (other.CanWrite))
other.SetValue(b, property.GetValue(a, null), null);
}
This?
static void Copy(object a, object b)
{
foreach (PropertyInfo propA in a.GetType().GetProperties())
{
PropertyInfo propB = b.GetType().GetProperty(propA.Name);
propB.SetValue(b, propA.GetValue(a, null), null);
}
}
If you will use it for more than one object then it may be useful to get mapper:
public static Action<TIn, TOut> GetMapper<TIn, TOut>()
{
var aProperties = typeof(TIn).GetProperties();
var bType = typeof (TOut);
var result = from aProperty in aProperties
let bProperty = bType.GetProperty(aProperty.Name)
where bProperty != null &&
aProperty.CanRead &&
bProperty.CanWrite
select new {
aGetter = aProperty.GetGetMethod(),
bSetter = bProperty.GetSetMethod()
};
return (a, b) =>
{
foreach (var properties in result)
{
var propertyValue = properties.aGetter.Invoke(a, null);
properties.bSetter.Invoke(b, new[] { propertyValue });
}
};
}
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