C# C# Collections Arrays Jagged Arrays

Garrosh HellScream
Garrosh HellScream
7,503 Points

How do you return a jagged array?

I eventually completed the challenge (with some help). Then I tried it in visual studio and fell flat on my face. Im unsure how to return the array. I keep getting .net system type as a return value system.int32[].

static void Main(string[] args) { int[][] display = BuildMultiplicationTable(3);

        foreach (var item in display)
        {
            Console.WriteLine(item);

        }

    }

    public static int[][] BuildMultiplicationTable(int maxFactor)
    {
        //create a var to hold the jagged array
        int[][] result = new int[maxFactor + 1][];

        for (int row = 0; row <= maxFactor; row++)
        {
            //create the new rows
            result[row] = new int[maxFactor + 1];

            for (int col = 0; col <= maxFactor; col++)
            {
                result[row][col] = row * col;
            }

        }
        return result;
    }

1 Answer

Christian ROLLET
Christian ROLLET
5,387 Points

A jagged array is an array containing arrays. BuildMultiplicationTable return what is expected (a jagged array)

The problem comes from your foreach loop. Inside item is an array of integer.

If you replace

foreach (var item in display)

By

foreach (int item in display)

You will have a compilation error.

And this should compile

foreach (int[] item in display)

You should try this last option, and add a new foreach loop inside.

Hope this help