Return to Snippet

Revision: 13634
at April 30, 2009 00:51 by rengber


Initial Code
//Lookup result of a higher level object which has a dogs list.   
    result.Dogs.ForEach(d => PopulateDogObject(d));     

//Helper
    public void PopulateDogObject(IDog toDog)
    {
        IDog lookupResult = GetDogFromWebService(toDog.DogID); 
        lookupResult.PopulateIDog(toDog); 
    }


//This is on the dog class.  
    public void PopulateIDog(IDog toDog)
        {
            PropertyInfo[] fromFields = typeof(IDog).GetProperties();
            foreach (PropertyInfo pi in fromFields)
            {
                pi.SetValue(toDog, pi.GetValue(this, null), null); 
            }
        }

Initial URL

                                

Initial Description
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.

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

Initial Tags
c, extension

Initial Language
C#