views:

28

answers:

1

For example, I have:

originalItem.Property1 = currentItem.Property1;
originalItem.Property2 = currentItem.Property2;
originalItem.Property3 = currentItem.Property3;
originalItem.Property4 = currentItem.Property4;

The properties will also change if the currentItem's property's value is different from that of originalItem's.

Any shortcuts here? Thanks.

A: 

Yes, you can do this via reflection.

Read the properties of both the instances and assign them with the help of reflection.

Here's some code..

    public static void AssignSourceToDestination(Object source, ref Object destination)
    {
        IList<PropertyInfo> sourceProps = source.GetProperties();
        IList<PropertyInfo> destProps = destination.GetProperties();

        foreach (PropertyInfo property in destProps)
        {
            if (property.CanWrite)
            {
                PropertyInfo sourceProp = sourceProps.Where(p => p.Name.Equals(property.Name) &&
                    p.PropertyType.Equals(property.PropertyType) && p.CanRead).First();
                if (null != sourceProp)
                    property.SetValue(destination, sourceProp.GetValue(source, null), null);
            }
        }
    }

    public static IList<PropertyInfo> GetProperties(this Object me)
    {
        return me.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
    }
this. __curious_geek