Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same Variable Names - 2 Different Classes - How To Copy Values From One To Another - Reflection - C#

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.

like image 338
Issa Fram Avatar asked May 19 '11 20:05

Issa Fram


3 Answers

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);
}
like image 199
Jan-Peter Vos Avatar answered Nov 05 '22 11:11

Jan-Peter Vos


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);
    }
}
like image 41
carlosfigueira Avatar answered Nov 05 '22 11:11

carlosfigueira


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 });
                   }
               };
}
like image 29
oxilumin Avatar answered Nov 05 '22 11:11

oxilumin