Building Your Own Generic List Class

Below is the complete code for the Building Your Own Generic List Class Try It Out! problem.

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

namespace Generics
{
    /// <summary>
    /// Defines a generic list, which is growable. New items can be
    /// added to it without concern for resizing the list, as that
    /// is managed for us.
    /// 
    /// This is a generic list, so it can be used with any specific type.
    /// </summary>
    public class PracticeList<T>
    {
        /// <summary>
        /// Stores the actual items as an array.
        /// </summary>
        private T[] items;

        /// <summary>
        /// Creates a new list. This list contains no values initially.
        /// </summary>
        public PracticeList()
        {
            items = new T[0];
        }

        /// <summary>
        /// Returns a specific item in the array. This would ideally be done
        /// with an indexer, which we talk about later on.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public T GetItem(int index)
        {
            return items[index];
        }

        /// <summary>
        /// Adds an item to the end of the list.
        /// </summary>
        /// <param name="newItem"></param>
        public void Add(T newItem)
        {
            // Create a new array that is one item bigger than before.
            T[] newItems = new T[items.Length + 1];

            // Copy all of the items from one array to another.
            for (int index = 0; index < items.Length; index++)
            {
                newItems[index] = items[index];
            }

            // In the last spot, place the new item.
            newItems[newItems.Length - 1] = newItem;

            // Reassign our backing array to the newly constructed,
            // and slightly larger array.
            items = newItems;
        }

        /// <summary>
        /// Returns the size of the list. 
        /// 
        /// This makes it much easier to loop over.
        /// </summary>
        public int Size
        {
            get
            {
                return items.Length;
            }
        }
    }
}