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);
}
}
}
Let me guess that your
ProjectContact
type is astruct
.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.
I can think of two possibilities: