How to change the value of a property given its name



  • In my program I have some classes where data is stored. For example

    Class1.alfa.dado = 66;
    Class1.beta.dado = 56;
    Class1.gama.dado = 37;
    

    The user will select in a ComboBox one of the options you want to change, in this ComboBox are the strings "alpha", "beta" and "gamma".

    So I need to run a function that does more or less so

    void change (string alterar)
    {
        Class1.(alterar).dado = 7;
    }
    

    How to use this "change" string to access the variable?

    A solution would be to use switch. But the problem is that the functions are not so simple, are big codes, and with the switch gets very repetitive and whenever I need to change something I have to move in a lot of places. I'd like to do that more automatically.



  • You can use a combination of:

    • PropertyInfo: Allows observation and manipulation of characteristics of types;
    • Convert.ChangeType: Allows change of types who implement IConvertible between formats during runtime.

    For example, your instance Class1.alfa could have the property dado dynamically changed as follows:

    string propriedade = "dado";
    string valor = "66";
    

    PropertyInfo propertyInfo = Class1.alfa.GetType().GetProperty(propriedade);
    propertyInfo.SetValue(Class1.alfa, Convert.ChangeType(valor, propertyInfo.PropertyType), null);




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2