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

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.

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: