Arrays first index displaying wrong element

I am currently studying C# language and getting 0 on the first index[0] where I am looking to see the user input which is "yx".

Here's what I have written:

using System;
namespace Examples
{
    class arrays
    {
        static void Main()
        {
            int[] y = new int[7];
            Console.WriteLine("Please enter your array y0: ");
            int yx = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please enter your array y2: ");
            int y2 = Convert.ToInt32(Console.ReadLine());
            foreach (var newemptyarray in y)
            {
                y[0] = yx;
                y[2] = y2;
                Console.WriteLine(newemptyarray);
            }
        }
    }
}

Please, can someone clarify the fact in details?

Jon Skeet
people
quotationmark

This loop doesn't do what the code suggests you think it does:

foreach (var newemptyarray in y)

That's iterating over the elements in y, which are integers. So newemptyarray isn't an array, it's just a value. On the first iteration of the loop, it will be the value of y[0]... but it's the value of y[0] before it enters the loop body, therefore it will always be 0. A foreach loop doesn't set up a special association with the array such that every time you access the iteration variable it fetches it from the array.

If you rearrange your code to:

y[0] = yx;
y[2] = y2;
foreach (var value in y)
{
    Console.WriteLine(value);
}

Then it will display yx, then 0 (for y[1]) then y2, then a bunch more zeroes.

You could also simplify the code to remove yx and y2 entirely, just assigning directly into the array:

int[] y = new int[7];
Console.WriteLine("Please enter your array y0: ");
y[0] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter your array y2: ");
y[2] = Convert.ToInt32(Console.ReadLine());
foreach (var value in y)
{
    Console.WriteLine(value);
}

people

See more on this question at Stackoverflow