-1

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!

1
  • Why you need that? If all variables have similar meaning you should put them in a double[] or List<double>. If you really need a mapping from the name to the value you could use a Dictionary<string, double>. Commented Aug 28, 2018 at 11:05

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.