How to add an element to a HashSet in C#

Add() method

The HashSet<T> generic class in the System.Collections.Generic namespace provides the Add() method, which can add an element to a HashSet in C#.

Syntax

public bool Add (T item);

Arguments

This method takes the following as input:

  • The item of type T which is to be added to the HashSet<T>.

Return values

  • The method returns true if the element is successfully added.

  • The method returns false if the element is already present in the HashSet.

Things to keep in mind

  • If the number of elements in the HashSet>T> already equals the capacity of the HashSet<T> object, its capacity is automatically adjusted to accommodate the new element.

  • This method is an O(1) operation if the number of elements is less than the capacity of the internal array.

  • If the HashSet<T> must be resized, this method becomes an O(n) operation, where “n” is the number of elements.

Adding an element to a HashSet using the Add() method

Code

We included the System.Collections.Generic namespace in our program.

using System;
using System.Collections.Generic;
class HashSetAdd
{
static void Main()
{
HashSet<string> monthSet = new HashSet<string>();
monthSet.Add("January");
monthSet.Add("February");
Console.WriteLine($"Added 'January' and 'February' to HashSet, Count: {monthSet.Count}");
bool result = monthSet.Add("January");
Console.WriteLine($"Adding 'Jaunary' again to the HashSet, result: {result}");
}
}

Explanation

  • In this example, we first created a HashSet of strings and have added two strings to it: "January" and "February".

  • Next, we try to add the "January" string to the HashSet again. Since it already exists, the Add() method returns false (which we have stored in the result variable).

Output

The program prints the below output and exits.

Added 'January' and 'February' to HashSet, Count: 2
Adding 'Jaunary' again to the HashSet, result: False

Free Resources