#280 – Implicitly-Typed Arrays

In the same way that you can declare an implicitly-typed variable, letting the compiler figure out the type of the variable’s value, you can declare implicitly-typed arrays.

In the example below, we declare and initialize both implicitly-typed variables and implicitly-typed arrays.  The compiler infers the type–shown in the associated comment.

            // Implicitly-typed variables
            var x = 42;         // int
            var s = "Hooey";    // string

            // Implicitly-typed arrays
            var someArray = new[] { 5, 6, 7 };             // int[]
            var arrB = new[] { new Dog("Bob"), null };     // Dog[]
Advertisements

#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);

#278 – Passing an Array by Reference

You can pass an array by reference to a method, using the ref or out parameter modifier, when you want the method to change the parameter to refer to a different array.

Here’s an example of a method that accepts an array and then overwrites the reference so that it points to a new array.

        public static void DoubleADogList(ref Dog[] list)
        {
            Dog[] bigList = new Dog[2 * list.Count()];

            int i2 = 0;
            foreach (Dog d in list)
            {
                bigList[i2++] = new Dog(d.Name, d.Age, d.Motto);
                bigList[i2++] = new Dog(d.Name + " Clone", d.Age, d.Motto);
            }

            // Change original reference to refer to new list
            list = bigList;
        }

We can call this method, passing it an array. When the method returns, the array variable points to the new (larger) array.

            Dog d1 = new Dog("Kirby", 13, "Chase balls");
            Dog d2 = new Dog("Jack", 17, "Bark");

            Dog[] list = new Dog[] { d1, d2 };

            Dog.DoubleADogList(ref list);

 

#277 – Passing an Array to a Method

A variable that is the name of an array is just a reference to an instance of System.Array.  Since it is a reference type, when you pass an array to a method, you pass a copy of the reference.  This means that the method has the ability to read and write elements of the array.

Here’s a method that accepts an array as an input parameter.  The code demonstrates that you can read from and write to elements of the array.

        public static void DumpMovieInfo(MovieInfo[] movieList)
        {
            for (int i = 0; i < movieList.Length; i++)
            {
                // Read element of the array
                Console.WriteLine("{0} ({1}), {2}", movieList[i].Title, movieList[i].Year, movieList[i].Director);

                // Rewrite element
                movieList[i].Title = movieList[i].Title.ToUpper();
                movieList[i].Director = movieList[i].Director.ToUpper();
            }
        }

You would call the method as follows:

            MovieInfo[] movies = { new MovieInfo("The African Queen", 1951, "John Huston"),
                                   new MovieInfo("Casablanca", 1942, "Michael Curtiz"),
                                   new MovieInfo("The Godfather", 1972, "Francis Ford Coppola")};

            Movie.DumpMovieInfo(movies);

            Movie.DumpMovieInfo(movies);

#276 – Passing a struct by Reference

You can pass a struct by reference using the ref or out parameter modifiers.  Use ref when you want a method to read and write to the struct.  Use out for a struct that is meant to be an output parameter.

Assuming that you’ve defined the following struct:

    public struct MovieInfo
    {
        public string Title;
        public int Year;
        public string Director;
    }

You might pass an instance of MovieInfo by reference like this:

        public static void DisplayThenUpper(ref MovieInfo minfo)
        {
            Console.WriteLine("{0} ({1}), {2}", minfo.Title, minfo.Year, minfo.Director);

            minfo.Title = minfo.Title.ToUpper();
            minfo.Director = minfo.Director.ToUpper();
        }

After we call the method, the contents of the struct have been modified.

            MovieInfo minf = new MovieInfo();
            minf.Title = "Citizen Kane";
            minf.Year = 1941;
            minf.Director = "Orson Welles";

            Movie.DisplayThenUpper(ref minf);

            Console.WriteLine("{0}, {1}", minf.Title, minf.Director);

Output after the program has finished:

#275 – Passing a struct to a Method

You can pass an instance of a struct type to a method.  By default, the struct is passed by value, which means that a copy of the struct’s data is passed into the method.  This means that the method cannot change the contents of the original struct.

For example, assume you’ve defined the following struct:

    public struct MovieInfo
    {
        public string Title;
        public int Year;
        public string Director;
    }

A method that accepts an instance of this struct as a parameter might look like:

        public static void DisplayMovieInfo(MovieInfo minfo)
        {
            Console.WriteLine("{0} ({1}), dir by {2}", minfo.Title, minfo.Year, minfo.Director);
        }

And calling the method would look like this:

MovieInfo minf = new MovieInfo();
minf.Title = "Citizen Kane";
minf.Year = 1941;
minf.Director = "Orson Welles";

Movie.DisplayMovieInfo(minf);   // Passed by value -- copy of minf passed to method

#274 – Can’t Overload if Methods Differ Only by ref and out Modifiers

You can overload a method in a class, i.e. define two methods with the same name, if the methods have different lists of parameters.  The parameter lists must differ in the number of parameters or in their types.

For example, we can overload the Dog.Bark method if the parameters differ only in type:

        public void Bark(int numBarks)
        {
            // implementation here
        }

        public void Bark(short numBarks)
        {
            // implementation here
        }

We cannot overload a method if the parameters differ only in a ref vs out modifiers:

        public void FindDog(ref Dog aDog)
        {
            // implementation here
        }

        // Compiler will disallow this overload
        public void FindDog(out Dog aDog)
        {
            // implementation here
        }