Copy All Object Values from Another Instance of the Same Type Using Reflection


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

Say that you have a collection of objects empty but for IDs.
You want to do a foreach loop through those objects and lookup detail one at a time.
Unfortunately, in the foreach, you can't replace the references, you can only copy the new detail into the object.
This technique will populate your current reference from an object instance returned by a lookup.


Copy this code and paste it in your HTML
  1. //Lookup result of a higher level object which has a dogs list.
  2. result.Dogs.ForEach(d => PopulateDogObject(d));
  3.  
  4. //Helper
  5. public void PopulateDogObject(IDog toDog)
  6. {
  7. IDog lookupResult = GetDogFromWebService(toDog.DogID);
  8. lookupResult.PopulateIDog(toDog);
  9. }
  10.  
  11.  
  12. //This is on the dog class.
  13. public void PopulateIDog(IDog toDog)
  14. {
  15. PropertyInfo[] fromFields = typeof(IDog).GetProperties();
  16. foreach (PropertyInfo pi in fromFields)
  17. {
  18. pi.SetValue(toDog, pi.GetValue(this, null), null);
  19. }
  20. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.