0

I would like to change the value of targeted properties within my object depending on the property's name. Example:

// Returns a list of all the properties of an object
PropertyInfo[] properties = GetProperties(myObject);

// Set the values of all properties that contain "Show_" in their name to -1
foreach (PropertyInfo property in properties)
{
    if (property.Name.Contains("Show_"))
    {
        // update myObject's property value to -1
        // i.e. something like:
        // myObject.(property.Name) = -1;
    }
}

How would I go about doing this?

Thanks

hyoung1484
  • 21
  • 1
  • 2
  • 1
    [Tagging help](https://stackoverflow.com/help/tagging): _"The only time you should use tags in your title is when they are organic to the conversational tone of the title."_ - as such I've removed the "(C#)" tag from your question title. – ProgrammingLlama Jun 11 '21 at 02:43
  • `property.SetValue(myObject, -1)` – John Wu Jun 11 '21 at 02:46
  • Does this answer your question? [Setting/getting the class properties by string name](https://stackoverflow.com/questions/10283206/setting-getting-the-class-properties-by-string-name) and [Can I set a property value with Reflection?](https://stackoverflow.com/questions/7718792/can-i-set-a-property-value-with-reflection) and [C# get and set property by variable name](https://stackoverflow.com/questions/11824362/c-sharp-get-and-set-property-by-variable-name) and [Refer to a property name by variable](https://stackoverflow.com/questions/13292078/refer-to-a-property-name-by-variable) –  Jun 11 '21 at 03:33

1 Answers1

2

You can use SetValue:

property.SetValue(myObject, -1, null);

You can read the documentation here.

StarshipladDev
  • 1,166
  • 4
  • 17
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86