C# `HashSet`: Working with Collections of Unique Elements

Learn how to use C#'s `HashSet` class for storing and managing collections of unique elements. This tutorial demonstrates adding elements, checking for existence, removing elements, and using collection initializers for efficient and concise `HashSet` creation and population.



Working with C#'s `HashSet` Class

The C# `HashSet` class is a collection that stores unique elements. Unlike lists, which can contain duplicates, a `HashSet` only keeps one instance of each item. This makes it ideal for scenarios where you need to ensure you have only unique values.

Key Features of `HashSet`

  • Stores Unique Elements: Duplicate elements are automatically ignored.
  • Efficient Lookup: Checking for the existence of an element is very fast.
  • Namespace: `System.Collections.Generic`

Adding Elements to a `HashSet`

You can add elements using the `Add()` method. If you try to add an element that already exists, the `Add()` method simply returns `false` without throwing an error.

Example 1: Adding Elements with `Add()`


using System;
using System.Collections.Generic;

public class HashSetExample {
    public static void Main(string[] args) {
        var names = new HashSet<string>();
        // ... (code to add names using Add(), iterate, and print) ...
    }
}

Example 2: Using Collection Initializers

A more concise way to create and populate a `HashSet` is to use collection initializers:


var names = new HashSet<string> { "Alice", "Bob", "Charlie" };