1

i have a case where i have several variables with similar names but not in an array. What i want to do is to pass the names of the variables to some function that i create and that function would return the value of the variable that was passed to the function by its name.

For example:

int valueByName(int x, string variableName){
   string newVar;
   string numString = x.ToString();
   newVar = variableName + numString;

   //and here i should get the value of newVar and return it to use it. but how?
   return valeuof(newVar);???
}

int num1 = 1;
int num2 = 2;
int num3 = 3;
string varName = "num";

for(int i = 1; i < 4; i++){
   Console.WriteLine(valueByName(i, varName));
}
fizi
  • 33
  • 4
  • All variables are of type `int`? Are they fields of some class? – Roman Feb 19 '17 at 10:14
  • 1
    You can't do it http://stackoverflow.com/questions/26463480/why-is-it-not-possible-to-get-local-variable-names-using-reflection – Guy Feb 19 '17 at 10:15
  • Let's say all the passed variables will have the same type in this example i just used int for simplicity. – fizi Feb 19 '17 at 10:16

1 Answers1

4

You can do this using .NET Reflection:

public class Foo
{
    private int field1 = 1;
    private int field2 = 2;
    private int field3 = 3;

    public int GetValueOf(string field)
    {
        FieldInfo f = this.GetType().GetTypeInfo().GetField(field, 
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        return (int)f.GetValue(this);
    }

}

Usage

var x = new Foo();
var y = x.GetValueOf("field2");

// y has value of 2

NOTE: .NET Reflection is not usually the best design choice because it doesn't perform very well. If performance is critical, I recommend you try to come up with a design that doesn't require you to lookup the value by name to avoid the performance impact this will incur.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212