I'm trying to code a method that will accept the following 3 arguments:
an Object (user defined type which will vary)
a string representing a property name for that object
a string value, which will have to be converted from a string to the property's data type prior to assignment.
The method signature will look like this:
public void UpdateProperty(Object obj, string propertyName, string value)
I've found how to retrieve a property value with Reflection with the following code:
PropertyInfo[] properties = target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in properties)
{
if (string.Compare(prop.Name, propertyName, true) == 0)
{
return prop.GetValue(target, null).ToString();
}
}
The problem is that I can't figure out how to set the property value. Also, the value is coming in as a string, so I have to check the data type of the value against the property's datatype before it can be cast & assigned.
Any help would be greatly appreciated.