0

So I'm trying to pass property values from an internal class to a public struct. Both have the same property names with same case. I'm getting no errors, but the properties in the struct are not getting set.

foreach (UserProfile.UserProfileRecord r in rslt.record)
{
    UserProfileRecord upr = new UserProfileRecord();
    Type uprType = upr.GetType();
    foreach (PropertyInfo p in r.GetType().GetProperties())
    {
        Debug.WriteLine(p.Name + " : " + p.GetValue(r));
        PropertyInfo pi = uprType.GetProperty(p.Name);
        pi.SetValue(upr, p.GetValue(r));
        Debug.WriteLine(pi.Name + " - " + pi.GetValue(upr));
    }
}

The output of the debug is as follows:

city : YERMO city -
state : CA state -
zip : 92398 zip -
telephone : 714-256-8463 telephone -

I've compared my code with several other examples on Microsoft and SO and I cannot see anything I'm doing wrong.

I pass the struct back to a caller and it's used as a DataSource for a DataGridView. The columns names appear but the cells are empty. When stopping at a break and looking at the struct, I see all property values are null.

What am I doing wrong?

tolsen64
  • 881
  • 1
  • 9
  • 22
  • You create a new instance, assign it to `upr`, and throw it away. Shouldn’t you be putting those in a list or something? – John Wu Jan 09 '19 at 04:21
  • 1
    Yes, I am adding them to a list, but didn't think it was relevant to the question. – tolsen64 Jan 09 '19 at 05:12
  • Struct is value-type. So, typically when you pass on the variable upr to pi.SetValue(upr, p.GetValue(r)) , it creates another copy of the variable and assigns value to the new one. You can box the upr to an object before you invoke SetValue method and unbox it later. This should fix it – Bharathi Jan 09 '19 at 05:16

0 Answers0