An Introduction to C# collections

I will give you an introduction to C# collections we often use in various applications. Collections will give you the ability to group related objects. Arrays provide the functionality of grouping the same type of objects and are static in nature. It may not shrink and grow as needed. On the other hand, your Collection object can shrink and grow as needed. Collections belong to System.Collections namespace. I will start with the introduction and after that I will deep dive into each of them in the next article.

We have various types of collections in C#. I will list them here.

1. Generic class Collections

Firstly, We use generic collections when every item in the collection has the same data type. Generic collections enforce strong type by allowing only desired data type. I added a table below to introduce you to the generic classes that are most frequently used. When I add more chapters on each of these I will provide you with hyperlinks. For now, I introduce you to the concepts of generic classes.

NameDescription
Dictionary<key, value> A collection of key-value pairs organized with respect to key
List<T>Collection of a list of objects that can be accessed by its index
Queue<T>A collection to represent objects where the first added will be the first removed (first in first out- FIFO).
SortedList<Key, Value>Similar to a dictionary except that the collection is sorted according to the key.
Stack<T>Represents the Last in first out collection of objects
Generic classes in C#

2. Concurrent classes

Secondly, I will talk about Concurrent classes in this paragraph. This gives an ability to access collections in a thread-safe environment. Similarly, we have concurrent collections for many of the generic classes. They are named as below.

  • ConcurrentDictionary<key,Value>
  • ConcurrentQueue<T>
  • ConcurrentStack<T>
  • BlockingCollection<T>(will discuss this later)

3. Other collection classes

In this paragraph, I will talk about all the other classes in collections. These do not store specifically typed objects. They have the type as ‘Object’ type. Microsoft recommends using the above two categories instead of this legacy type collection. The following classes are most frequently used.

NameDescription
ArrayListAn array of objects whose size can be increased dynamically.
HashTableA collection of key-value pairs.
QueueFIFO type of representation
StackLIFO type of representation
Legacy types

In conclusion, We learned in brief about various collections in C#. Let us begin our journey to C# collections in the next article.

Want to code in C#? Click here and try out.

Prev: Arrays Introduction

Next: ArrayList Collection