0

I would be thankful if someone help me to resolve some task.
I need to create several variables using cycle "for".

I ask users how many numbers will they input, and declare it like variable "countVariables".
Next step, using cycle "for" I want to create new variables using counter cycle`s "for".

For example, name of created var must be like "num1", "num2", "num3" etc. I try do it using a code below.

I understand, that it isn't good solution, but I need to resolve task just using this way.

Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
    
for (int i = 1; i <= countVariables; i++)
{
    string tmp = "num" + i;
    int tmp.name = Console.ReadLine();
}
Markus Meyer
  • 3,327
  • 10
  • 22
  • 35
  • 8
    no, you don't need to create several variables. you need to create one _array_ – Franz Gleichmann Aug 15 '22 at 09:42
  • 1
    You can potentially do this using code generation and runtime compilation, but it is a huuuuuuuge overkill when you can use some collection (list, array, dictionary, based on the use case will do). – Guru Stron Aug 15 '22 at 09:44
  • The duplicates provide answers to the question you asked but, as others have said, it would be better not to use Reflection, just use some sort in indexed collection. – Jodrell Aug 15 '22 at 10:05

2 Answers2

3

You can't do it using variables as you've mentioned but you can use Arrays instead. After reading number of times to repeat, you can create an array based on that then access values by index:

Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);

var data = new string[countVariables];

for (int i = 1; i <= countVariables; i++)
{
    string tmp = "num" + i;
    data[i] = Console.ReadLine();
}

Later after the for loop you can access your values using data[0], data[1]... or use another for loop for looping over the values.

Fadi Hania
  • 705
  • 4
  • 11
0

You can use a Dictionary for storing the data:

var data = new Dictionary<int, string>();
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);

for (int i = 1; i <= countVariables; i++)
{
    var val = Console.ReadLine();
    data.Add(i, val);
}

Write out number on index '4':

Console.WriteLine(data[4]);
Markus Meyer
  • 3,327
  • 10
  • 22
  • 35