Variables in a loop

You don’t want 3 variables with the same name, you want an array of those variables.

string[] messages = new string[3]; // 3 item array

You can then store your items in the array elements

messages[0] = "Apple"; // array index starts at 0!
messages[1] = "Banana";
messages[2] = "Cherry"; 

Another way to create that array is an inline array initializer, saves some code

string[] messages = { "Apple", "Banana", "Cherry" }; 

(Note: there are more valid syntaxes for array initialization. Research on the various other methods is left as an exercise.)

And access them via a loop (foreach)

foreach (string fruit in messages)
{
    Console.WriteLine("I'm eating a " + fruit);
}

Or for

for (int i = 0; i < messages.Length; i++)
{
    Console.WriteLine("I'm eating a " + messages[i]); // reading the value
    messages[i] = "blabla" + i.ToString(); // writing a value to the array
}

Leave a Comment