1

Let's say I have 4 strings.

private string string_1, string_2, string_3, string_4;

Then let's say I have a for loop. How can I access the variable name by the index of the for loop? Here's an idea of what I'm talking about:

for(int i = 0; i < 4; i++)
{
    string_ + i = "Hello, world! " + i;
}

I understand that doing the above will not compile.

Thanks for your help.

3 Answers3

2

You can't do what you're asking - at least directly.

You could start with simply putting the strings into an array and then work from the array.

string[] strings = new []
{
    string_1,
    string_2,
    string_3,
    string_4,
};

for(int i = 0; i < 4; i++)
{
    strings[i] = "Hello, world! " + i;
}

Console.WriteLine(string_3); // != "Hello, world! 2"
Console.WriteLine(strings[2]); // == "Hello, world! 2"

But then the original string_3 is unchanged, although its slot in the array is correct.

You can go one step further and do it this way:

Action<string>[] setStrings = new Action<string>[]
{
    t => string_1 = t,
    t => string_2 = t,
    t => string_3 = t,
    t => string_4 = t,
};

for(int i = 0; i < 4; i++)
{
    setStrings[i]("Hello, world! " + i);
}

Console.WriteLine(string_3); // == "Hello, world! 2"

This works as originally intended - string_3 does get updated. It is a little contrived though, but may be useful to you.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1
string[] hello = new string[4];
for(int i = 0; i < 4; i++)
{
    hello[i] = "Hello, world! " + i;
}

If you want a variable-length list, use a type that implements ICollection<string>, for instance Dictionary<string>, HashSet<string> or List<string>.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
ChrisV
  • 1,309
  • 9
  • 15
-1

Put your strings into an array, then use the for loop to iterate through the array. As you iterate through the array call your command on the ith element of your array.

String[ ] array = ["a", "b","c"];
for(int i = 0; i < array.length ; i++)
// print array[i]