C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# HashSet, Queue and Stack

C# HashSet, Queue and Stack

Specialised collections for unique sets, FIFO queues, and LIFO stacks.

1 - HashSet<T> — Unique Values

var tags = new HashSet<string> { "csharp", "dotnet", "programming" };
tags.Add("csharp");     // ignored — already exists
tags.Add("linq");       // added

Console.WriteLine(tags.Count);          // 4
Console.WriteLine(tags.Contains("linq")); // true

// Set operations
var a = new HashSet<int> { 1, 2, 3, 4 };
var b = new HashSet<int> { 3, 4, 5, 6 };

a.IntersectWith(b);   // {3,4}
a.UnionWith(b);       // {1,2,3,4,5,6}
a.ExceptWith(b);      // {1,2}

2 - Queue<T> — First In, First Out

var queue = new Queue<string>();
queue.Enqueue("Task 1");
queue.Enqueue("Task 2");
queue.Enqueue("Task 3");

Console.WriteLine(queue.Peek());    // "Task 1" (peek without removing)
Console.WriteLine(queue.Dequeue()); // "Task 1" (remove and return)
Console.WriteLine(queue.Count);     // 2

3 - Stack<T> — Last In, First Out

var stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);

Console.WriteLine(stack.Peek()); // 3 (peek)
Console.WriteLine(stack.Pop());  // 3 (remove and return)
Console.WriteLine(stack.Pop());  // 2
// Useful for: undo history, expression parsing, DFS traversal

Note: HashSet<T> has O(1) Contains() — dramatically faster than List<T>'s O(n) linear scan. Use it whenever you need to track a set of unique items and check membership frequently.

-Tip-

C# {"id":42,"topic_id":3,"name":"C# Collections","slug":"c-collections","image":null,"description":"<p>Generic collections in C# \u2014 List, Dictionary, Queue, Stack, HashSet, and more.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":11,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: