-3

I have a cube1, cube2, cube3 etc... variables and i want to use something like that:

for (int i = 1; i < 100; i++)
{
    Location "cube + i" = new Location();
    Console.WriteLine("cube + i + .GetX")
}

// GetX is a function that gives a random number

  • 7
    Look at using arrays, lists or dictionaries – Lee Taylor May 06 '22 at 22:25
  • If GetX is a "function" it should have `()` after it. In C# we generally call code that "does stuff" a *method*, not a function (and in your case GetX is quite likely to be a method). Strive to use the terms other C# devs use because you may one day have a method that contains a local function and if you call the method a function when saying something like "I'm getting a null reference exception in my function" you might cause confusion in the minds of those reading your code – Caius Jard May 07 '22 at 05:20

1 Answers1

3

use an array

var cubes = new Location[100];
for (int i = 0; i < 100; i++)
{
    cubes[i] = new Location();
    Console.WriteLine(cubes[i].GetX);
}

or a list - if you are not sure how many and want to add later

var cubes = new List<Location>();
for (int i = 1; i < 100; i++)
{
    cubes.Add(new Location());
    Console.WriteLine(cubes[i].GetX);
}
pm100
  • 48,078
  • 23
  • 82
  • 145
  • @Александр Indeed, every time you find yourself in a situation where you have x1, x2, x3 and you're thinking "how can I variable-ize that 1,2,3 part of the name" then you need an array. It helps my students to think of an array variable name as having a part that is fixed and a part that can be changed programmatically; for you the `cube` part never changes and the `[...]` part does. If it's an array of size 3 then you have `cube[0]` instead of `cube1`, `cube[1]` instead of `cube2`, `cube[2]` instead of `cube3`, and so on. Remember they start from 0, so adjust your mental model to be off-by-1 – Caius Jard May 07 '22 at 05:15
  • Thank you, you're a god! I've used a array. List throws a "System.ArgumentOutOfRangeException" Exception – Александр Третинов May 09 '22 at 13:39
  • @АлександрТретинов chnage the i=1 to i=0, my mistake – pm100 May 09 '22 at 14:44
  • @pm100 Thank you, but i already found it) – Александр Третинов May 09 '22 at 15:56