#279 – Passing a Multidimensional Array to a Method

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.

        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.

            ChessPiece[,] board = new ChessPiece[8, 8];

            board[0, 1] = new ChessPiece(PieceTypeEnum.King, PieceColorEnum.Red);
            // continue to set up board here

            int redPawns;
            int blackPawns;
            Chess.CountPawns(board, out redPawns, out blackPawns);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #279 – Passing a Multidimensional Array to a Method

  1. Joe says:

    You must be a checkers player because I’ve never seen a red pawn! P.S. Thanks a lot for making this blog, it’s been very informative so far.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: