You can pass multi-dimensional arrays to methods. Like arrays with a single dimension, the array is passed by value, with a copy of the reference passed to the method. This means that the method can change elements in the array.
Here’s an example of a method that takes a two-dimensional array as an input parameter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| public static void CountPawns(ChessPiece[,] chessboard, out int redPawns, out int blackPawns){ redPawns = 0; blackPawns = 0; for (int row = 0; row < 8; row++) for (int col = 0; col < 8; col++) { ChessPiece piece = chessboard[row,col]; if (piece != null) { if (piece.PieceType == PieceTypeEnum.Pawn) { if (piece.PieceColor == PieceColorEnum.Red) redPawns++; else blackPawns++; } } }} |
When calling the method, you just pass the name of the array to the method.
1
2
3
4
5
6
7
8
| ChessPiece[,] board = new ChessPiece[8, 8];board[0, 1] = new ChessPiece(PieceTypeEnum.King, PieceColorEnum.Red);// continue to set up board hereint redPawns;int blackPawns;Chess.CountPawns(board, out redPawns, out blackPawns); |

