2

I'm trying to code a method that will accept the following 3 arguments:

  1. an Object (user defined type which will vary)

  2. a string representing a property name for that object

  3. 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.

JM.
  • 678
  • 12
  • 23

3 Answers3

4

SetValue with Convert.ChangeType should work for you. Using your code:

newValue = Convert.ChangeType(givenValue, prop.PropertyType);
prop.SetValue(target, newValue, null);
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
  • Austin, You're the MAN! This worked great. I used var as the type declaration for newValue ( newValue = Convert.ChangeType(givenValue, prop.PropertyType);) – JM. Mar 20 '11 at 21:33
1

SetValue is what you are looking for.

There are plenty of questions on here with sample code (take a look at the Related Question list on the right of this page)

e.g. Setting a property by reflection with a string value

Community
  • 1
  • 1
Stuart
  • 66,722
  • 7
  • 114
  • 165
1
prop.SetValue(target,new TypeConverter().ConvertFromString(propertyValue));
BFree
  • 102,548
  • 21
  • 159
  • 201
  • This didn't compile for me without a third argument (null) and then it errored with "TypeConverter cannot convert from System.String." I'm not sure. In either case I need to attempt conversion to a specific datatype (prop.PropertyType). – JM. Mar 20 '11 at 21:28