views:

48

answers:

2

I've simplified the code below down to a basic example, but I still cannot get the value to set. When performing the propertyInfo.SetValue(), it will hit a breakpoint on the setter of my Contact object and the value is set correctly in the 'setter.' However, after the SetValue() has executed, the string properties on my projectContact.Contact object have not been changed to "a". Any idea what I could be doing wrong here?

IEnumerable<ProjectContact> contacts = GetContactsByProject(projectId);

        foreach (ProjectContact projectContact in contacts)
        {
            foreach (PropertyInfo propertyInfo in projectContact.Contact.GetType().GetProperties())
            {
                if (propertyInfo.PropertyType == typeof(string))
                {
                    propertyInfo.SetValue(projectContact.Contact, "a", null);
                }
            }
        }
+5  A: 

I can think of two possibilities:

  1. The property setter isn't working correctly on the property. It may be setting a different field than the property getter, so when you set the property, you never actually "set" the real value.
  2. If "Contact" is a struct (value type), projectCOntact.Contact will return a copy of the struct. This will prevent you from ever changing the "real" object.
Reed Copsey
Yep, you nailed it! It's a struct, not by my choice :) Learned something new today!
JSprang
+3  A: 

Let me guess that your ProjectContact type is a struct.

Since structs are passed by value, you're setting the value on a copy of the struct, which is then discarded.
This is why mutable structs are evil and should be avoided at all costs.

You should change your ProjectContact type to a class.


It's also possible that you have a bug in your setter.

SLaks