This post will discuss how to initialize a HashSet<T> in C#.

We can use object initializers to initialize a HashSet<T> in C#, introduced in C# 3.0. It consists of a sequence of elements, enclosed within { and } where each member is separated by a comma. This causes each of the specified elements to be added to the HashSet<T> object, without explicitly invoking the constructor.

The following example shows how to initialize a new HashSet<int> by using object initializers.

Download  Run Code

 
Alternatively, you can invoke the HashSet<T> constructor to initialize a new instance of the HashSet<T> class with elements of the specified collection. For example, the following code initializes a HashSet<T> with distinct elements of a List<T>, in no particular order.

Download  Run Code

 
If you need to add the specified element to an existing HashSet<int> object, consider using the standard Add method. The following code example demonstrates this:

Download  Run Code

That’s all about initializing a HashSet<T> in C#.