3

This is my try, which doesn't work (I'm a beginner). The idea is to have an simple two dimensional array of Kid.years ints to understand how to use the foreach with objects.

    using System;

        namespace Test
        {
            class Kid
            {
                public int years;
            }
            class Program
            {
                static void Main()
                {
                    Kid[,] array = new Kid[4, 5];
                    for (int counter = 0; counter < 4; counter++)
                    {
                        for (int counter2 = 0; counter2 < 5; counter2++)
                        {
                            array[counter, counter2] = new Kid();
                            array[counter, counter2].years = counter + 1000;
                        }
                    }
                    foreach (int item in array[,].years)
                    {
                        Console.WriteLine(item);
                    }
                }
            }
        }

3 Answers3

4

You can enumerate two dimensional array as below:

foreach (Kid item in array)
{
    Console.WriteLine(item.years);
}   
Mustafa Ekici
  • 7,263
  • 9
  • 55
  • 75
2

Just change to it:

foreach (var item in array)
{
     Console.WriteLine(item.years);
}

see it working in my fiddle: https://dotnetfiddle.net/Sfi0yu

Joel R Michaliszen
  • 4,164
  • 1
  • 21
  • 28
  • Thank you very much, now I understand that I should have used the var instead of int! –  Jan 07 '16 at 03:13
0

I think you might want to introduce for and foreach differences in handling multidimensional arrays but example you shown is not applicable to do that.

Although below code [][] is not exactly 2d arrays, named jagged arrays, but explaining for and foreach case will be more suitable.

        static void Main()
        {
            Kid[][] array = new Kid[4][];
            for (int counter = 0; counter < 4; counter++)
            {
                array[counter] = new Kid[5];
                for (int counter2 = 0; counter2 < 5; counter2++)
                {
                    array[counter][counter2] = new Kid();
                    array[counter][counter2].years = counter + 1000;
                }
            }

            // how to use foreach.
            foreach (Kid[] item in array)
            {
                foreach (var kid in item)
                {
                    Console.WriteLine(kid.years);
                }
            }
            Console.ReadLine();
        }

If you want to see differences of [][] and [,] in image, please see this well explained link: https://stackoverflow.com/a/12567550/361100

Community
  • 1
  • 1
Youngjae
  • 24,352
  • 18
  • 113
  • 198