C# – Create and populate multidimensional array representing minesweeper-type grid


I'm trying to create a multidimensional array to contain arrays of cartesian coordinates (x,y) in a multidimensional array of [X,Y] width and height.

This is where I've gotten to so far; I've become hopelessly confused…

int[][][] grid = new int[width][][];
    for (int x = 0; x < width; x++)
        grid[x] = new int[height][];
        for (int y = 0; y < height; y++)
           grid[y] = new int[2][];

    foreach (int[][] coordinate in grid)

For example, I'd like a 3 x 4 grid to be represented by an array as such:

{1, 1}, {2, 1}, {3, 1}
{1, 2}, {2, 2}, {3, 2}
{1, 3}, {2, 3}, {3, 3}
{1, 4}, {2, 4}, {3, 4}


I've scoured the web for a solution in C# (I'm a relative newcomer to OO, unfamiliar with C, C++ etc.) but have so far drawn a blank.

Am I on the right track in the approach I've taken with the creation of the array?
Can anyone offer some tips on how to populate the array with the coordinates, using loops if possible?

Best Solution

Instead of having a multidimensional array, you could create a class to hold the coordinates (and other stuff related to each tile).

For example, it could look like this :

public class Tile
    public int X {get; set;}
    public int Y {get; set;}
    public bool HasMine {get; set;}

So instead of having a multidimensional array, you could use a simple List<Tile> to hold all your tiles. All you have to do to populate that list is create a new Tile instance for every tiles, like this :

List<Tile> tiles = new List<Tile>();

for(int i = 0; i < NB_HORIZONTAL_TILES; i++)
    for (int j = 0; j < NB_VERTICAL_TILES; j++)
        tiles.Add(new Tile { X = i; Y = j });

To iterate over them, you can simply use a foreach statement or some LINQ. That would be a more OO way to solve the problem.