Thursday, July 18, 2013

Copy Property Values

If you have 2 objects that do not inherit from each other but have similar properties, here is a function you can use to copy property values from one object to the other:

    public static void CopyIdenticalProperties (this object source, object dest)
        {
            var plist = from prop in source.GetType().GetProperties()
                        where prop.CanRead && prop.CanWrite
                        select prop;

            foreach (PropertyInfo prop in plist)
            {
                var destProp = dest.GetType().GetProperty(prop.Name);              
                if (destProp != null)
                {
                    destProp.SetValue(dest, prop.GetValue(source, null), null);
                }
            }
        }