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.
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! Source: https://ru.stackoverflow.com/questions/891530/
All Articles
nameof(...)typenameof(...)then there is no such analog for your question. - Zergatuls, and for the same source, but with the variableq. - PashaPash ♦