0

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Indexed property is the best of both worlds - access using array like syntax, but wrapped in a getter/setter for encapsulation
1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.