Search code examples
c#dynamic-variables

How to access var by constructing name using variable and a string


In PHP you can do the following to access a variable:

$foobar1 = 00.00;
$foobar2 = 11.11;
$foobar3 = 22.22;
$i = 2;

echo ${'foobar' . $i}; //Prints 11.11

I want to do the same in C# but I can't seem to get this to work:

double foobar1 = 00.00;
double foobar2 = 11.11;
double foobar3 = 22.22;
int i = 2;

Print("foobar" + i); //Should print 11.11

Any ideas? I have tried a few different searches but I can't seem to find what I'm looking for.

Cheers!


Solution

  • There is no way to dynamically reference a variable by constructing its name. You can use reflection for properties, etc.

    I would recommend using an array or list:

    double[] foobar = { 00.00, 11.11, 22.22 };
    int i = 2 - 1; // arrays are 0-based
    
    Print(foobar[i]); //Does print 11.11