Trying to construct a map with 2-D arrays

I am trying to construct a map with coordinates -20 to 20 for the x-axis and y axis with C#. At the moment i have defined my ranges(as shown below) and i am using a for each loop to loop through both lists however i can't populate them with anything because it throws an error when i try and reassign the array values back. I would like to draw a map with points. Is my logic wrong?

IEnumerable<int> squares = Enumerable.Range(-20, 20);
IEnumerable<int> cirles = Enumerable.Range(-20, 20); 

int [][] arrays = new int[squares.Count()][cirles.Count()];

            foreach (var shape in squares)

                foreach (var sha in cirles)

\\Construct map

The program throws a type error as it wants me to print out a jagged array to define it like this int [][] arrays = new int[squares.Count()][];

The error is invalid rank or specifier,

1 answer

  • answered 2017-06-17 19:20 dnickless

    As mentioned in the comments already you are probably attempting to use the wrong kind of array here. It seems like you'd be better off simply using a 2D array since your dimensions are fixed:

    int[,] array = new int[squares.Count(), circles.Count()];

    If you want to stick with a jagged array make sure you understand this first:

    Jagged arrays cannot be initialized the way you tried it. I suppose the reason for that is that it just wouldn't make an aweful lot of sense. Jagged arrays allow you to have different dimensions for each contained array (which you don't need).

    Still, if you want to use a jagged array then use the following code instead for the initialization:

        int[][] arrays = new int[squares.Count()][];
        for (int i = 0; i < arrays.Length; i++)
            arrays[i] = new int[circles.Count()];