Search code examples
c#arraysgetter-setter

Using the adressed index in an array setter / setter


I want to properly handle indexes out of bounds in the getters and setters of an array (not by exception handlers), like this (which does not work):

byte[] Board {
    get {
        if (index >= 0 && index < Board.Length)
            return Board[index];
        else
            return 3;
    }
    set {
        if (index >= 0 && index < Board.Length)
            Board[index] = value;
    }
}

So that, e.g. Board[1] returns the content of Board[1] and Board[-1] returns 3.

What would be the correct way to do this?


Solution

  • In C# properties can only get/set "themselves". That means that if you have an array you can only get/set the array itself, not individual values. You can, however, create methods that look and act the way you want like this:

    public byte getBoardValue(int index) {
      if (index >= 0 && index < Board.Length)
        return _board[index];
      else
        return 3;
    }
    
    public void setBoardValue(int index, byte value) {
      if (index >= 0 && index < Board.Length)
            _board[index] = value;
    }