This post will discuss how to create a copy of a HashSet<T> in C#.

The HashSet<T> class provides a Constructor that takes a collection and initializes a new instance of the HashSet<T> class with the elements copied from the specified collection. The following example demonstrate creating a new HashSet<T> instance from an existing Set.

Download  Run Code

 
You can also create a ToHashSet extension method to create a copy of a HashSet<T> is using its constructor, as shown below:

Download  Run Code

 
The HashSet<T> class provides has another overload that ensures the same equality comparer is used as the original Set. For example, the following code uses a supplied comparer to allow case-insensitive comparisons on the elements of a HashSet<T> collection.

Download  Run Code

That’s all about creating a copy of a HashSet<T> in C#.