user1460211
user1460211

Reputation: 39

Accessing a variable's name by using index of for loop

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.

Upvotes: 1

Views: 1128

Answers (3)

ChrisV
ChrisV

Reputation: 1309

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>.

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117175

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.

Upvotes: 2

Alexander Sobin
Alexander Sobin

Reputation: 59

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] 

Upvotes: -1

Related Questions