[Solved] how to declare multiple variable names with loop in c#


Well, if I am interpreting your question right, you can declare an array or list, then initialize these elements in a loop

For example (array) (if you want a fix number of elements):

int n = 10; // number of strings

string[] str = new string[n]; // creates a string array of n elements

for (int i = 0; i < n; i++) {
    str[i] = ""; // set the value "" at position i in the array
}

(list) (if you don’t want a fix number of elements)

using System.Collections.Generic;

...
int n = 10;
List<string> str = new List<string>(); // creates a list of strings
// List<string> str = new List<string>(n) to set the number it can hold initially (better performance)

for (int i = 0; i < n; i++) {
    list.Add(""); // if you've set an initial capacity to a list, be aware that elements will go after the pre allocated elements
}

list[0] = "hello world"; // how to use a List
list[list.Count - 1] = "i am the last element"; // list.Count will get the total amount of elements in this list, and we minus 1 to fix indexing

3

solved how to declare multiple variable names with loop in c#