1

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?

Pekler
  • 23
  • 5
  • Yes, you can do this. It would be better to remove the `set;` accessors, otherwise the user of the object could change e.g. the value of `rows` and the array will not reflect this. – Klaus Gütter Feb 17 '22 at 12:25
  • The answer you linked just warns that any user of the class can change the contents of your `grid` without the class being aware of this. This might or might not be an issue. – Klaus Gütter Feb 17 '22 at 12:27

1 Answers1

0

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).

PMF
  • 14,535
  • 3
  • 23
  • 49