internal static void UpdateObject(object source, object dest, bool checkUpdatable, DateTime?updateTime) { if (dest == null || source == null) { throw new ArgumentNullException(); } Type destType = dest.GetType(); if (!destType.IsInstanceOfType(source)) { throw new ArgumentException(String.Format("Can not copy values from type {0} to type {1}", source.GetType().Name, destType.Name)); } // for things that are IUpdatable, let them do the copy. // IUpdatable updateable = dest as IUpdatable; if (checkUpdatable && updateable != null) { updateable.UpdateFrom(source); if (updateTime.HasValue) { updateable.LastUpdated = updateTime.Value; } } else { // otherwise use reflection to copy the values over. // foreach (var prop in destType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { try { if (prop.CanWrite && prop.CanRead) { var v = prop.GetValue(source, null); prop.SetValue(dest, v, null); } } catch (Exception ex) { Debug.WriteLine("Failed to update property {0}.{1} on type {2} ({3})", destType.Name, prop.Name, source.GetType().Name, ex.Message); } } } }