简体   繁体   中英

C# Public variables in a class

I have a class which has a 2D jagged array declared in it's constructor, and in that class I have two methods called GetXY and SetXY, that modify said array.

However, I am unsure whether I should use these methods or in fact declare the grid as public, meaning there would be 2 ways of setting and reading values in the array, like this:

    ProceduralGrid pg = new ProceduralGrid(10, 10);

    pg.grid[0][0] = 2;
    pg.SetXY(0, 0, 2);

Which one shall I use, and why?

Why not use

    public T this[int x, int y]
    {
        get
        {
            return grid[x][y];
        }
        set
        {
            grid[x][y] = value;
        }
    }

Naturally check for valid x and y etc...

Use methods to access the array. Either SetXY or an indexer as suggested be Alessandro. That way, you can later change the implementation without changing your class interface.

It is best to use methods to set variables that are used inernally.

This way you can protect your inner object and are free to implement extra validation or modify the object as required.

This allows you to easily change the behaviour of that object later on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM