Simple, Quality, Awesome Software

Copying an Array

Below is the complete code for the Copying an Array Try It Out! problem.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CopyingAnArray
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create the initial array.
            int[] numbers = new int[] { 4, 5, 2, 3, 1, 0, 8, 9, 7, 6 };

            // Note that while you can do this, this doesn't make a
            // copy. They'll both be the exact same array. Modifying
            // one will affect the other. For more about this, see
            // the chapter on value and reference types.
            // int[] copy = numbers;

            // Copy the values from one array to a copy.
            int[] copy = new int[numbers.Length];
            for (int index = 0; index < numbers.Length; index++)
            {
                copy[index] = numbers[index];
            }

            // Print out the original array.
            for (int index = 0; index < numbers.Length; index++)
            {
                Console.Write(numbers[index] + " ");
            }
            Console.WriteLine();

            // Print out the copy.
            for (int index = 0; index < copy.Length; index++)
            {
                Console.Write(copy[index] + " ");
            }
            Console.WriteLine();
            Console.WriteLine();

            Console.ReadKey();
        }
    }
}