-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

2
  • 7
    Look at using arrays, lists or dictionaries Commented May 6, 2022 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 Commented May 7, 2022 at 5:20

1 Answer 1

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

4 Comments

@Александр 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
Thank you, you're a god! I've used a array. List throws a "System.ArgumentOutOfRangeException" Exception
@АлександрТретинов chnage the i=1 to i=0, my mistake
@pm100 Thank you, but i already found it)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.