How to use HashSet in C#

A HashSet is an optimized collection of unordered, unique elements that provides fast lookups and high-performance set operations. The HashSet class was first introduced in .NET 3.5 and is part of the System.Collection.Generic namespace. This article talks about how we can work with HashSets in C#.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core Console Application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core Console Application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project to work with HashSet in the subsequent sections of this article.

What is a HashSet?

A HashSet — represented by the HashSet<T> class pertaining to the System.Collections.Generic namespace — is a high-performance, unordered collection of unique elements. Hence a HashSet is not sorted and doesn’t contain any duplicate elements. A HashSet also doesn’t support indices — you can use enumerators only. A HashSet is usually used for high-performance operations involving a set of unique data.

The HashSet<T> class implements several interfaces as shown below:

Copyright © 2020 IDG Communications, Inc.


Leave a Reply