Link to home
Start Free TrialLog in
Avatar of prosperion
prosperion

asked on

Accessing C# Variables...

Hi,

I have a class which has three variables defined:
   > int a
   > int b
   > int c

And a function:
  > SetVariableValue(String variable, int value)

I need to be able to call the function, SetVariableValue("b", 23), which sets the variable b to the value 23.

How do I go about setting a variable, when I only have a string which represents it?

Thanks,
Tym.
Avatar of mrichmon
mrichmon

I think that you would need to use reflection to do this.

Otherwise you could have a struct or some other object like a dictionary instead of the variables itself so like this:

Dictionary<string, int> myInts = new Dictionary();

// initialize
myInts["a"] = 0;
myInts["b"] = 0;
myInts["c"] = 0;

Then later
SetVariableValue("b", 23) would look like:

public void SetVariableValue(string key, int value)
{
   myInts[key] = value;
}
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Keep in mind that reflection is very, very slow (compared to an IDictionary), so I'd avoid it if at all possible.
You can use in the SetVariableValue a switch:

public void SetVariableValue(string variable, int value)
{
    switch (variable)
    {
          case ("a"):
          {
                this.a = value;
                break;    
          }              
          case ("b"):
          {
                this.b = value;
                break;    
          }
          case ("c"):
          {
                this.c = value;
                break;    
          }
    }
}

Hope it helps.
Regards,
Mishu
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial