Easy Tutorial
❮ Csharp Program Structure Csharp Break Statement ❯

C# Collection

The Collection class is specifically designed for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces.

Collection classes serve various purposes, such as dynamically allocating memory for elements, accessing list items by index, and more. These classes create collections of objects from the Object class. In C#, the Object class is the base class for all data types.

Various Collection Classes and Their Uses

Below are various commonly used classes from the System.Collection namespace. Click on the links below to see details.

Class Description and Usage
ArrayList It represents an ordered collection of objects that can be individually indexed. It essentially serves as an alternative to an array. However, unlike arrays, you can add and remove items at a specified position using an index, and the ArrayList will automatically resize itself. It also allows dynamic memory allocation, addition, searching, and sorting of items in the list.
Hashtable It uses a key to access the elements in the collection. When you use a key to access elements, you use a hashtable, and you can identify a useful key value. Each item in the hashtable has a key/value pair. The key is used to access the items in the collection.
SortedList It can be accessed using keys and indexes. A sorted list is a combination of an array and a hashtable. It contains a list that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The items in the collection are always sorted by the key value.
Stack It represents a last-in, first-out collection of objects. Use a stack when you need last-in, first-out access to items. When you add an item to the list, it is called pushing the element, and when you remove an item, it is called popping the element.
Queue It represents a first-in, first-out collection of objects. Use a queue when you need first-in, first-out access to items. When you add an item to the list, it is called enqueue, and when you remove an item, it is called dequeue.
BitArray It represents an array of binary values, represented by 1s and 0s. Use a BitArray when you need to store bits but do not know the number of bits in advance. You can access items from the BitArray collection using an integer index, which starts at zero.
❮ Csharp Program Structure Csharp Break Statement ❯