Clone from one object to another using Reflection


/ Published in: C#
Save to your folder(s)

Copy from one object to another of the same type


Copy this code and paste it in your HTML
  1. public static void ShallowCopy(Object dest, Object src)
  2. {
  3. BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
  4. FieldInfo[] destFields = dest.GetType().GetFields(flags);
  5. FieldInfo[] srcFields = src.GetType().GetFields(flags);
  6.  
  7. foreach (FieldInfo srcField in srcFields)
  8. {
  9. FieldInfo destField = destFields.FirstOrDefault(field => field.Name == srcField.Name);
  10.  
  11. if (destField != null && !destField.IsLiteral)
  12. {
  13. if (srcField.FieldType == destField.FieldType)
  14. destField.SetValue(dest, srcField.GetValue(src));
  15. }
  16. }
  17. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.