2

I have a sample class

public class sampleClass
{
    public string givenName { get; set; }
    public string familyName { get; set; }
}

and a set of values for that class contained in IDictionary<string, object> dataModel. I can use reflection to iterate through the dataModel and use the dataModel key to get the value.

I would like to do something like:

void UpdateValues(IDictionary<string, object> dataModel)
{
    Type sourceType = typeof(sampleClass);
    foreach (PropertyInfo propInfo in (sourceType.GetProperties()))
    {
        if (dataModel.ContainsKey(propInfo.Name))
        {
            //  set propInfo value here
            propInfo.Value = dataModel[propInfo.Name];
        }
    }
}

But i have no idea how to do the line

propInfo.Value = dataModel[propInfo.Name];

Help! Thanks !!

nawfal
  • 70,104
  • 56
  • 326
  • 368
Peter Smith
  • 5,528
  • 8
  • 51
  • 77

2 Answers2

5

you need an instance of the sampleClass to set the property on and then you can use the SetValue function to do that:

propInfo.SetValue(yourinstance, dataModel[propInfo.Name], null);

see this URL: http://msdn.microsoft.com/en-us/library/axt1ctd9.aspx

1
propInfo.SetValue(sampleClass, dataModel[propInfo.Name], null)
nawfal
  • 70,104
  • 56
  • 326
  • 368
Greg Oks
  • 2,700
  • 4
  • 35
  • 41