Is it possible to use a dynamic variable (not sure about naming) in C#?
In PHP, I can do
$var_1 = "2";
$var_2 = "this is variable 2";
$test = ${"var_".$var_1};
echo $test;
output: this is variable 2;
Can we do this in C#?
Is it possible to use a dynamic variable (not sure about naming) in C#?
In PHP, I can do
$var_1 = "2";
$var_2 = "this is variable 2";
$test = ${"var_".$var_1};
echo $test;
output: this is variable 2;
Can we do this in C#?
No, basically. The compiler doesn't guarantee that method variables will exist (in their form as written), or with names...
If they were fields (instance or static), then you could use reflection to get the values; but not method variables. For what you want, perhaps use a dictionary as a substitute?
You are not looking for simple arrays?
Otherwhise dictionary is the way to go.
Not sure if this works with local variables (and most likely it doesn't since they're stored as indexes), but you could access class properties through reflection.
If your
var
is a class field, then you can use the staticGetField
method from classType
to obtain field information, such as its current value.In C#, you use dictionaries to associate values with strings.