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

1. Using HashSet<T>.Add() Method

The HashSet<T> class is a collection that contains all unique elements, in no particular order. The HashSet<T> class provides the standard method Add which adds the specified element to it. It returns true if the element is added to the HashSet<T> and false if the element is already present.

The following example creates a HashSet<T> object and demonstrates the usage of the Add() method.

Download  Run Code

2. Using HashSet<T>.UnionWith() Method

The HashSet<T>.UnionWith() method modifies the HashSet to contain all elements that are present in itself, the specified collection, or both. It can be used to add multiple values to an existing HashSet<T> object, as shown below:

Download  Run Code

That’s all about adding elements to a HashSet<T> in C#.