-1

Generally, we declare variable with specific name. int x=1; int life2 = 100;

But what if i want to declare group of variable with some specific index like this x1 , x2, x3, ... x(n) Instead of manually brute force declare int x1,x2,x3,x4,..... x(n); How can i achieve this by not using array or list?

I uncertainly remember this can achieve by using loop and some special syntax like

for(int f1=0;f1<10;f1++)
{
 string temp = ""+f1;
 int x+temp; //something
 .
 .
 .
}

Please help. Thank you.

2 Answers2

1

Maybe you can use an ExpandoObject whose members can be added and removed at run time.

For example:

dynamic expandoObject = new ExpandoObject();

for (int i = 0; i < 100; i++)
{
    ((IDictionary<string, object>) expandoObject)["x" + i] = i;
}

Console.WriteLine(expandoObject.x1);  //Will write 1
Console.WriteLine(expandoObject.x2);  //Will write 2
Console.WriteLine(expandoObject.x50); //Will write 50
Alberto
  • 15,626
  • 9
  • 43
  • 56
0

No, this syntax does not work in C#. You will need to use an array or a list.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300