Skip to content

Collections

Collections in C# provide various ways to work with groups of related objects. They offer different features for storing, managing, and manipulating groups of items, each optimized for specific scenarios.

Arrays

Arrays are fixed-size collections that store elements of the same type in a contiguous block of memory. They provide fast access to elements using an index.

csharp
// Declaration
int[] numbers = new int[5];
string[] names = { "John", "Jane", "Bob" };

// Access
int firstNumber = numbers[0];

Lists

Lists are dynamic collections that can grow or shrink in size. They provide flexible ways to add, remove, and manipulate elements.

csharp
List<string> names = new List<string>();
names.Add("John");
names.AddRange(new[] { "Jane", "Bob" });
names.Remove("Bob");

Dictionary

Dictionaries store key-value pairs, allowing you to access values using unique keys. They provide fast lookups and are ideal for mapping relationships.

csharp
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages["Jane"] = 30;

if (ages.ContainsKey("John"))
{
    int johnsAge = ages["John"];
}

HashSet

HashSets store unique elements in an unordered collection. They automatically handle duplicates and provide fast lookups.

csharp
HashSet<int> uniqueNumbers = new HashSet<int>();
uniqueNumbers.Add(1);
uniqueNumbers.Add(2);
uniqueNumbers.Add(1); // Ignored (duplicate)