Search code examples
c#propertyinfo

Increment "PropertyInfo SetValue"


This is my code:

        Enemy ble = new Enemy();
        PropertyInfo prop = ble.GetType().GetProperty("x");
        prop.SetValue(ble,20, null);
        Console.WriteLine(prop.GetValue(ble));

class Enemy
{
    public int x { get; set; } = 20;
}

As you can see I have an Enemy class and I've already found out how to find that property "x" and change it's value to set value, in my example 20, but my question is, how can I increment or decrement its value by 2 for example?


Solution

  • You have already used GetValue() and SetValue(), get its value, add to it, and then again set the new value:

    prop.SetValue(ble,(int)prop.GetValue(ble) + 2, null);