Add()
methodThe HashSet<T>
generic class in the System.Collections.Generic
namespace provides the Add()
method, which can add an element to a HashSet in C#.
public bool Add (T item);
This method takes the following as input:
HashSet<T>
.The method returns true if the element is successfully added.
The method returns false if the element is already present in the HashSet.
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.
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}");}}
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).
The program prints the below output and exits.
Added 'January' and 'February' to HashSet, Count: 2
Adding 'Jaunary' again to the HashSet, result: False