Posted By

rengber on 04/30/09


Tagged

c extension Reflection


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

umang_nine
vali29


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


 / Published in: C#
 

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.

  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  

You need to login to post a comment.