Is it possible to somehow define a variable by its name as a string?

For example:

int s = 0; FindVar("s") = 25; Console.WriteLine(s.ToString()); // 25 

I know that the function is possible, but the variable is of interest.

  • one
    It seems to me not, since the function is part of the metadata, that is, part of the type that is stored in memory. And a variable is just a named reference to a section of memory, its name is not stored anywhere - tym32167
  • @ tym32167 and how then does the compiler understand that such a variable already exists in this area of ​​the code, and does not allow it to be re-created? isn't it just a string processing? - Vitaly Shebanits pm
  • So the compiler understands this, but at the time of execution nothing can be found. If you are interested in some kind of C # nameof(...) type nameof(...) then there is no such analog for your question. - Zergatul
  • No, it is impossible - the names of local variables do not survive compilation. Those. the output will be the same IL code for the name of the variable s , and for the same source, but with the variable q . - PashaPash
  • Thank you all for your attention. sorry of course ... but okay - Vitaly Shebanits

2 answers 2

You cannot do this with a local variable, since the compiler has the right not to use any variables at all or to assign its own names to them.

If you make a variable a member of a class - a field or a property, then the problem will become solvable: you can get to the members of the class using reflection:

 class Data { public int a, b, c; public void SetField(string name, int value) { var field = typeof(Data).GetField(name); field.SetValue(this, value); } } 

Then:

 var data = new Data(); Console.WriteLine(data.a); // 0 data.SetField("a", 10); Console.WriteLine(data.a); // 10 

    Can.
    Use Dictionary.

     //Заполнение: Dictionary<string, object> vars = new Dictionary<string, object>(); vars["переменная1"] = 20; vars["переменная2"] = "Hello, world"; //Вывод: Console.WriteLine(vars["переменная1"]); //20 Console.WriteLine(vars["переменная2"]); //Hello, world!