Home > Net >  How to iterate through a C# object's properties and update the corresponding property on anothe
How to iterate through a C# object's properties and update the corresponding property on anothe

Time:12-11

I have to objects of the same type, one source and one destination. What I'm attempting to do is iterate through the source object properties, and if it has a value, update the corresponding property on the second. I think I have the first part:

foreach (PropertyInfo prop in object1.GetType().GetProperties())
{ 
     var val = property.GetValue(object1)
     if (val != null)
     {
         --code to update object2 current prop
     }
}

I figure that there must be a way to directly reference the property on object2 without having to iterate through and compare each name and type. Hope so anyway.

CodePudding user response:

The function you're looking for is SetValue, like so:

prop.SetValue(object2, val);
  • Related