Forenkazan
Forenkazan

Reputation: 107

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.

Upvotes: 1

Views: 45

Answers (1)

itsme86
itsme86

Reputation: 19496

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

Upvotes: 2

Related Questions