class CarMaker
{
public void MakeNewCar(int carCount)
{
string[] names = new string[carCount];
Random random = new Random();
for (int i = 0; i < carCount; i++)
{
int randomNum = random.Next(0, 3);
Car **howCanIDo** = new Car(null, (EModels)randomNum, (EColor)randomNum);
}
}
}
Asked
Active
Viewed 632 times
-2

Gilad Green
- 36,708
- 7
- 61
- 95

검은촛대
- 9
-
Please explain what are you trying to achieve by doing so? what is the logic you want? – Gilad Green Dec 13 '19 at 08:50
-
Please check https://stackoverflow.com/a/5033731/6923146 – Hardik Masalawala Dec 13 '19 at 08:50
-
why do you want to? What are you going to do with the cars? I suspect you want a list and you can add each to the list without each having a unique name – NDJ Dec 13 '19 at 08:51
-
Does this answer your question? [Create dynamic variable name](https://stackoverflow.com/questions/20857773/create-dynamic-variable-name) – Hardik Masalawala Dec 13 '19 at 08:51
-
What you are trying to do is impossible, but you can achieve the same functionality with arrays, dictionaries... – Carlos López Marí Dec 13 '19 at 08:59
1 Answers
3
By the collection names
I assume you want to "hold" all the "names" (actually the references) to the Car
objects you create in the loop. What you could do is instead have an array of type Car
and add the items to it:
Car[] cars = new Car[carCount];
Random random = new Random();
for (int i = 0; i < carCount; i++)
{
int randomNum = random.Next(0, 3);
cars[i] = new Car(null, (EModels)randomNum, (EColor)randomNum);
}
And maybe even more convenient would be to just use lists:
List<Car> cars = new List<Car>();
for (int i = 0; i < carCount; i++)
{
int randomNum = random.Next(0, 3);
cars.Add(new Car(null, (EModels)randomNum, (EColor)randomNum));
}

Gilad Green
- 36,708
- 7
- 61
- 95