Forenkazan Forenkazan - 1 year ago 72
C# Question

C#: How can I assign a value to a variable by passing a string of its name?


int XValue;
int YValue;

void AssignValue(string VariableName,int VariableValue)
VariableName = VariableValue;

void CallAV()
AssignValue("XValue", 10);
AssignValue("YValue", 15);


So, basically i want to change the value of a variable by knowing its name.

Answer Source

What you're looking for is collectively called Reflection. Specifically, you want to use Type.GetField(). You could do something like this:

void AssignValue(string VariableName, int VariableValue)
    // Get the non-public instance variable (field)
    FieldInfo field = GetType().GetField(VariableName, BindingFlags.NonPublic | BindingFlags.Instance);

    // Set the variable's value for this instance of the type
    field.SetValue(this, VariableValue);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download