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.
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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;
}