C#: A generic class called Collection

This entry is part 64 of 71 in the series C#

We have looked at generic method and constructed a generic class.  As mentioned earlier, generic classes are commonly used in WPF data binding in updating ListBox, ListView and ComboBox.

We look at a generic Collection class provided by Microsoft.  The example creates a collection of strings, uses the Add method to add several strings, displays the Count, and lists the strings.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace CollectionDemo
{
    class Program
    {
        public static void Main()
        {
            Collection<string> city = new Collection<string>();

            city.Add("Paris");
            city.Add("New York");
            city.Add("London");
            city.Add("Moscow");

            Console.Write("{0} city:", city.Count);
            Display(city);

            Console.Write("\nIndexOf(\"Moscow\"): {0}", city.IndexOf("Moscow"));

            Console.Write("\nContains(\"New York\"): {0}", city.Contains("New York"));

            Console.WriteLine("\nInsert(2, \"Beijing\")");
            city.Insert(2, "Beijing");
            Display(city);

            Console.WriteLine("\ncity[2]: {0}", city[2]);

            Console.WriteLine("\ncity[2] = \"Tokyo\"");
            city[2] = "Tokyo";
            Display(city);

            Console.WriteLine("\nRemove(\"Tokyo\")");
            city.Remove("Tokyo");
            Display(city);

            Console.WriteLine("\nRemoveAt(0)");
            city.RemoveAt(0);
            Display(city);

            Console.WriteLine("\ncity.Clear()");
            city.Clear();
            Console.WriteLine("Count: {0}", city.Count);
            Console.ReadKey();
        }

        private static void Display(Collection<string> cs)
        {
            Console.WriteLine();
            foreach (string item in cs)
            {
                Console.WriteLine(item);
            }
        }
    }
}

collection

Series Navigation<< C#: Generic classes
C#: Random number generation >>