Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Collections in C#

What are Collections?

Collections in C# are used to group related objects together. Collections are classes that are used to store and manage groups of objects. They provide a more flexible way to work with groups of objects compared to arrays.

Types of Collections

C# provides several types of collections, each suitable for different scenarios. The most commonly used collections are:

  • ArrayList
  • List<T>
  • Dictionary<TKey, TValue>
  • Queue<T>
  • Stack<T>

ArrayList

An ArrayList is a non-generic collection of objects whose size increases dynamically. It can store items of different types.

Example:
ArrayList arrayList = new ArrayList();
arrayList.Add(1);
arrayList.Add("Hello");
arrayList.Add(true);

// Accessing elements
Console.WriteLine(arrayList[0]);  // Output: 1
Console.WriteLine(arrayList[1]);  // Output: Hello
Console.WriteLine(arrayList[2]);  // Output: True
                    

List<T>

A List<T> is a generic collection that can store elements of a specific type. It provides methods to manipulate the list easily.

Example:
List numbers = new List();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

// Accessing elements
Console.WriteLine(numbers[0]);  // Output: 1
Console.WriteLine(numbers[1]);  // Output: 2
Console.WriteLine(numbers[2]);  // Output: 3
                    

Dictionary<TKey, TValue>

A Dictionary<TKey, TValue> is a collection of key/value pairs. It is optimized for fast lookups using keys.

Example:
Dictionary ages = new Dictionary();
ages["Alice"] = 30;
ages["Bob"] = 25;

// Accessing elements
Console.WriteLine(ages["Alice"]);  // Output: 30
Console.WriteLine(ages["Bob"]);    // Output: 25
                    

Queue<T>

A Queue<T> represents a first-in, first-out (FIFO) collection of objects.

Example:
Queue queue = new Queue();
queue.Enqueue("First");
queue.Enqueue("Second");
queue.Enqueue("Third");

// Accessing elements
Console.WriteLine(queue.Dequeue());  // Output: First
Console.WriteLine(queue.Dequeue());  // Output: Second
Console.WriteLine(queue.Dequeue());  // Output: Third
                    

Stack<T>

A Stack<T> represents a last-in, first-out (LIFO) collection of objects.

Example:
Stack stack = new Stack();
stack.Push("First");
stack.Push("Second");
stack.Push("Third");

// Accessing elements
Console.WriteLine(stack.Pop());  // Output: Third
Console.WriteLine(stack.Pop());  // Output: Second
Console.WriteLine(stack.Pop());  // Output: First