0

I have a class with a list of variables (shortened to one "a" here) - I'm trying to create a way to populate a variable based on two string inputs, so I can just use, for instance:

SET_VAL("a", "value_for_a")

Which I'd like to get the MessageBox showing just "value_for_a"

but I'm tripping up trying to use reflection, I'm sure this is possible, I know it's possible to get a value from a variable using a string to find it's name, cos every time I search for this that's all I seem to get, but why doesn't the following work? The method SetValue is asking for objects as parameters when I just want to pass two strings?

public class MySystem_SubsNote
   {
       public string a;

       public void SET_VAL(string mytype, string myvalue)
       {
            this.GetType().GetField(mytype).SetValue(myvalue);
            MessageBox.Show(a);
       }
   }
    
         
jamheadart
  • 4,270
  • 4
  • 19
  • 50

1 Answers1

3

As mentioned from Lasse in the comments SetValue expects two parameters, the first being the instance of which to set the value, the second the new value. So this should do it:

public void SET_VAL(string mytype, string myvalue)
{
    this.GetType().GetField(mytype).SetValue(this, myvalue);
    MessageBox.Show(a);
}
HimBromBeere
  • 32,045
  • 4
  • 46
  • 84
  • Thanks, this makes sense but now I'm getting `Object reference not set to an instance of an object.` on this line. I don't understand since I've set an instance of it in another method, and am using `this` - when highlighted - `this` shows the object/class type – jamheadart May 04 '18 at 07:56
  • then I suppose `GetField` does return `null`. Maybe you have a typo in your field-name? – HimBromBeere May 04 '18 at 07:57
  • I just recreated this as a mini-project and it worked fine so I think there may be a hidden space in my field-name on my large project (it's parsed separately from a huge string list) - thanks for the advice, marking this as best answer since it definitely works! – jamheadart May 04 '18 at 08:07
  • Just FYI it wasn't the field that was an issue, I had replaced "GetField" with "GetProperty" while I was trying different things and forgot to change it back :/ – jamheadart May 04 '18 at 08:47