Posted By

rralhan on 07/17/14


Tagged

copy clone Reflection shallowCopy


Versions (?)

Clone from one object to another using Reflection


 / Published in: C#
 

Copy from one object to another of the same type

  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
Posted By: rralhan on July 17, 2014

Copy from one object to another object of the same type

You need to login to post a comment.