Forenkazan Forenkazan - 3 months ago 7
C# Question

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

Example:

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

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);
}