I want to create class that draws a board. I wrote code like this (it works):
{
public class Map
{
public int rows { get; set; }
public int cols { get; set; }
public int[,] grid { get; set; }
public Map(int rows, int cols)
{
this.rows = rows;
this.cols = cols;
this.grid = new int[rows, cols];
}
public void printBoard()
{
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
Console.Write(grid[r, c] + "");
}
Console.WriteLine();
}
}
}
//Program.cs:
Map map = new Map(2, 2); map.printBoard();
Questions i have: 1.Can I create array as property and then initialize it(idk how to call it) in constructor as in the code above? I read here that i shoud't do it but maby that was not the case https://stackoverflow.com/a/18428679 2. If it's ok, is it good practice to write code like this, maby I coud write it better?
set;accessors, otherwise the user of the object could change e.g. the value ofrowsand the array will not reflect this.gridwithout the class being aware of this. This might or might not be an issue.