0

I am brushing up and reviewing some of my C# notes.

I'm running one of his examples for the first time and I am getting this error: Cannot convert type double to double[] error. To me, the code looks good, I don't know why it's not converting. Why is this line causing an error?

    class Program
    {

        static void Main(string[] args)
        {
            double[,] list1;
            int r = 5, c = 10;
            list1 = new double[r, c];

            for(int i = 0; i < r; i++)
                for(int j = 0; j<c; j++)
                    list1[i,j] = Convert.ToDouble(Console.ReadLine());

            foreach (double [] i in list1)  // -- THIS LINE IS GIVING ME THE ERROR --
            {
                foreach (double j in i)
                    Console.WriteLine(j);
            }

            Console.Read();
        }
    }
  • 2
    `double[][]` != `double[,]`; the first is an array of arrays of doubles `(double[])[]` and the second is a two dimensional array of doubles – D. Ben Knoble Sep 29 '15 at 22:06

2 Answers2

0

You can tell the type of the elements in the array by the line in your code:

list1[i,j] = Convert.ToDouble(Console.ReadLine());

The array contains doubles, not arrays

Two dimensional arrays in C# are real arrays, not array of arrays

AD.Net
  • 13,352
  • 2
  • 28
  • 47
0

Multidimensional arrays aren't enumerable per se. You can iterate by index like this:

for (int i = 0; i < list1.GetLength(0); i++)
{
    for (int j = 0; j < list1.GetLength(1); j++)
    {
        Console.WriteLine(list1[i, j]);
    }
}

Which is in your example equivalent to treating it like a one-dimensional array:

foreach (double d in list1)
{
    Console.WriteLine(d);
}
nharrer
  • 618
  • 7
  • 21