Generic Collection in C#:

You have learned about the collection in the previous section, e.g. ArrayList, BitArray, SortedList, Queue, Stack and Hashtable. These types of collections can store any type of items. For example, ArrayList can store items of different data types:

Example: C# Collection

ArrayList arList = new ArrayList();


The limitation of these collections is that while retrieving items, you need to cast into the appropriate data type, otherwise the program will throw a runtime exception. It also affects on performance, because of boxing and unboxing.

To overcome this problem, C# includes generic collection classes in the System.Collections.Generic namespace.

The following are widely used generic collections:

Generic Collections Description
List<T> Generic List<T> contains elements of specified type. It grows automatically as you add elements in it.
Dictionary<TKey,TValue> Dictionary<TKey,TValue> contains key-value pairs.
SortedList<TKey,TValue> SortedList stores key and value pairs. It automatically adds the elements in ascending order of key by default.
Hashset<T> Hashset<T> contains non-duplicate elements. It eliminates duplicate elements.
Queue<T> Queue<T> stores the values in FIFO style (First In First Out). It keeps the order in which the values were added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection.
Stack<T> Stack<T> stores the values as LIFO (Last In First Out). It provides a Push() method to add a value and Pop() & Peek() methods to retrieve values.

A generic collection gets all the benefit of generics. It doesn't need to do boxing and unboxing while storing or retrieving items and so performance is improved.

Learn generic collectoin List<T> in the next section.