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?
CodePudding user response:
As described in the answer you link to, properties should not normally return arrays, because that exposes the internals of a class to the outside, without the control over what is part of the array. The way you have declared your property, a client can insert arbitrary values into the array and your class has no way of performing any validation.
By convention, properties should use capital names as well. But in your case, the right thing to do is make all your properties fields and make them private. Then add an indexer to update the array (Note that it is even possible to change rows
and cols
from outside, which will most certainly result in undefined behavior).