Home > Software engineering >  Get 2D list value with Point for input (C#)
Get 2D list value with Point for input (C#)

Time:10-20

For uni I'm programming this game where there is a grid int[,] grid;. I also have this class:

public class Point
    {
        public int x;
        public int y;

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        public static Point operator  (Point a, Point b)
        => new Point(a.x   b.x, a.y   b.y);
    }

Representing points in this grid. Is there a way to access values of this grid using points? So say you want the value of the grid at (2, 3), you would access this by grid[new Point(2,3)]?

CodePudding user response:

With int[,] grid;, No, you can't.

But, you can wrap int[,] grid; with a class and use Indexer Property like this

public class GridWrapper : Tuple<int, int>
{
    // This is your grid data
    public int[,] Grid { set; get; } 

    // Indexer Property
    public int this[Point point] => Grid[point.x, point.y];

    public GridWrapper(int dim1, int dim2) : base(dim1, dim2)
    {
        Grid = new int[dim1, dim2];
    }
}

Now, this will work

var value = grid[new Point(1, 2)];

Full example

// define a grid
var grid = new GridWrapper(3, 3);

// mock data
for (int i = 0; i < 3; i  )
for (int j = 0; j < 3; j  )
    grid.Grid[i, j] = i   j;

// getting a value using the Indexer Property
var value = grid[new Point(1, 2)];
  • Related