We can define a generic collection which is a collection of any type that you specify. For example, we can use the List<T> class fro the System.Collections.Generics namespace. The List<T> can a collection of objects of T type. So List<int> for example, will be a collection of integer values.

using System;
using System.Collections.Generic;

namespace GenericCollectionDemo
{
    public class Animal
    {
        public string Type;

        public Animal(string type)
        {
            Type = type;
        }
    }
    public class Program
    {
        public static void Main()
        {
            List<Animal> animals = new List<Animal>();

            animals.Add(new Animal("Dog"));
            animals.Add(new Animal("Cat"));
            animals.Add(new Animal("Rat"));

            foreach (Animal animal in animals)
            {
                Console.WriteLine(animal.Type);
            }
        }
    }
}

Example 1 – Using the List<T> Generic Collection

Dog
Cat
Rat

The List<T> class also offers AddRange()Remove()RemoveAt() and other methods that we used on our collection class in the previous lessons.

You can also use the Dictionary<TKey, TVal> class that also resides in the same namespace. The TKey determines the type of the key (usually string), and the TVal specifies the type of the value.

using System;
using System.Collections.Generic;

namespace GenericCollectionDemo2
{
    public class Animal
    {
        public string Type;

        public Animal(string type)
        {
            Type = type;
        }
    }
    public class Program
    {
        public static void Main()
        {
            Dictionary<string, Animal> animals = new Dictionary<string, Animal>();

            animals.Add("Animal1", new Animal("Dog"));
            animals.Add("Animal2", new Animal("Cat"));
            animals.Add("Animal3", new Animal("Rat"));

            foreach (Animal animal in animals.Values)
            {
                Console.WriteLine(animal.Type);
            }
        }
    }
}

Example 2 – Using the Dictionary<K,V> Generic Dictionary

We defined a dictionary that has string keys and Animal values. To iterate through the dictionary items, you can use the Valuesproperty which contains all the items in the dictionary. You can also use the Keys property to get all the keys in the dictionary.

The classes we presented are quite similar to the collection and dictionary classes that inherit from CollectionBase and DictionaryBase classes. But we don’t need to create those collection classes anymore. The List<T> and Dictionary<TKey, TVal>made it instant just by supplying the type of the items. You may still prefer using custom collections and dictionaries if you want to add additional functionality for the AddRemove and other common methods.