English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Generic and non-generic collections

C# includes specialized classes for storing a series of values or objects, which are called collections.

There are two types of collection types available in C#: non-generic collections and generic collections.

The System.Collections namespace contains non-generic collection types, and the System.Collections.Generic namespace includes generic collection types.

In most cases, it is recommended to use generic collections, as they execute faster than non-generic collections and also minimize exceptions by providing compile-time errors.

Generic collections

C# includes the following generic collection classes in the System.Collections.Generic namespace.

Generic collectionsDescription
List<T>

Generic List<T> contains elements of a specified type. When you add elements to it, it will automatically grow.

Dictionary<TKey,TValue>Dictionary<TKey,TValue> contains key-value pairs.
SortedList<TKey,TValue>

SortedList stores key-value pairs. By default, it automatically adds elements in ascending order of keys.

Queue<T>

Queue<T> stores values in a First In, First Out (FIFO) style. It maintains the order of values added. It provides an Enqueue() method to add values, as well as a Dequeue() method to retrieve values from the collection.

Stack<T>Stack<T> stores values in Last In, First Out (LIFO) order. It provides a Push() method to add values, as well as Pop() and Peek() methods to retrieve values.
Hashset<T>Hashset<T> contains non-repetitive elements. It eliminates duplicate elements.

Non-generic collections

Non-generic collectionsUsage
ArrayList

ArrayList can store objects of any type, such as arrays. However, unlike arrays, you do not need to specify the size of ArrayList, as it will automatically grow.

SortedList

SortedList stores key-value pairs. By default, it automatically arranges elements in ascending order of keys. C# includes both generic and non-generic SortedList collections.

Stack

The Stack stores these values in a Last In, First Out (LIFO) manner. It provides a Push() method to add values, as well as Pop() and Peek() methods to retrieve values. C# includes both generic and non-generic stacks.

Queue

Queue stores values in a first-in-first-out (FIFO) manner. It maintains the order of the values added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection. C# includes both generic and non-generic queues.

Hashtable

Hashtable stores key-value pairs. It retrieves the value by comparing the hash value of the key.

BitArray

BitArray manages a compact array of bit values, represented by boolean values, where true means the bit is on(1) false means the bit is off.

In the next chapter, let's see each type of collection.