C# Hashset - C# Tutorial
C# Course / Collections / C# Hashset

C# Hashset

BLUF: Mastering C# Hashset is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: C# Hashset

C# is a powerful, modern language for enterprise solutions. Discover how C# Hashset enhances your development workflow in the guide below.

The C# HashSet class enables storage, removal, and viewing of elements without allowing duplicates. Opt for the HashSet class when you need to maintain a collection of distinct elements. This class is located within the System.Collections.Generic namespace.

C# HashSet__PRESERVE_5__ example

Let's examine a sample HashSet<T> class that is generic in nature, storing elements through the Add function and iterating over elements using a for-each loop.

Example

using System;

using System.Collections.Generic;



public class HashSetExample

{

    public static void Main(string[] args)

    {

        // Create a set of strings

        var names = new HashSet<string>();

        names.Add("Sonoo");

        names.Add("Ankit");

        names.Add("Peter");

        names.Add("Irfan");

        names.Add("Ankit");//will not be added

        

        // Iterate HashSet elements using foreach loop

        foreach (var name in names)

        {

            Console.WriteLine(name);

        }

    }

}

Output:

Output

Sonoo

Ankit

Peter

Irfan

C# HashSet__PRESERVE_7__ example 2

Let's explore an additional illustration of a generic HashSet<T> class that stores elements through a Collection initializer.

Example

using System;

using System.Collections.Generic;



public class HashSetExample

{

    public static void Main(string[] args)

    {

        // Create a set of strings

        var names = new HashSet<string>(){"Sonoo", "Ankit", "Peter", "Irfan"};

        

        // Iterate HashSet elements using foreach loop

        foreach (var name in names)

        {

            Console.WriteLine(name);

        }

    }

}

Output:

Output

Sonoo

Ankit

Peter

Irfan

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience