S
S
Solomon Gennadievich2021-11-30 13:36:41
C++ / C#
Solomon Gennadievich, 2021-11-30 13:36:41

C# Is it possible to declare "global" variables inside a loop?

Is it possible to declare variables inside a loop? To declare, instead of stupidly to reassign values.

Example: you run the for loop 20 times and as a result you get 20 variables of the form:
peremen1 = 1,
peremen2 = 1,
peremen3 = 1,
...etc

Which will work outside the loop further along the code

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-11-30
@destroyerkgb

You need a List

// Заранее объявляем наш список
var data = new List<int>();

for(var i = 0; i < 10; i++) {
  data.Add(i); // В цикле добавляем в него значения.
}

// теперь у нас есть список data, в котором лежат числа от 0 до 9 (10 штук)
// К ним в дальнейшем можно обратиться так:
Console.WriteLine(data[0]); // Печатаем первое число из списка
Console.WriteLine(data[9]); // Печатаем десятое число из списка.
Console.WriteLine(data[^1]); // Обращаемся к первому с конца (последнему)

G
GavriKos, 2021-11-30
@GavriKos

Discover Arrays/List/Dictionary.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question