1

I have a program in which a user types in the name of the variable they want to change. So we have this:

string user_input = "age";

And I have a class with the following:

class Jim{
    public static int age = 10;
    public static bool married = false;
    public static string name = "John";
} 

I now want to print the value of the variable that the user entered. So since the user typed in age I want to print Jim.age. How can I convert user_input into something that lets me access the class. I really want to do Jim[input_string] like you can in JS, but I believe this is possible.

I would use a dictionary to store all of the variables associated with Jim but you can't make a Dictionary which maps as <string, bool or int or string>.

Nick Chapman
  • 4,402
  • 1
  • 27
  • 41

2 Answers2

2

I would use a dictionary to store all of the variables associated with Jim but you can't make a Dictionary which maps as <string, bool or int or string>.

Sure you can, a Dictionary<string, object>. string, bool, and int can all be stored in a variable of type object.

Servy
  • 202,030
  • 26
  • 332
  • 449
0

The normal way to do this would be to use reflection:

FieldInfo requestedField = typeof(Jim).GetField("age");
Console.WriteLine(requestedField.GetValue(instanceOfJim));

Unfortunately, you can't do this because your variables are static. Make them instance members and it would work. As commenters have noted, allowing users to perform reflection is not a very good idea, so you may want to rethink the use case in general.

You could also use a dictionary mapped to object, as Servy suggested.

Interestingly enough, it can work with static, as long as you put the method in the Jim class:

class Jim
{
   ...Member variables...
   public static GetMember(String name)
   {
      FieldInfo requestedField = typeof(Jim).GetField(name);
      return requestedField.GetValue(null);
   }
}

Again, not recommending this, but it will get the functionality you want.

In case you are wondering, the MSDN for FieldInfo.GetValue: MSDN

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117