dimanche 19 février 2017

How to pass the name of variable to a function and return its value in C#?

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





Aucun commentaire:

Enregistrer un commentaire