Language

HashSet.Add(T) Method

Definition

Adds the specified element to a set.

public:
 virtual bool Add(T item);
public:
 bool Add(T item);
public bool Add(T item);
abstract member Add : 'T -> bool
override this.Add : 'T -> bool
member this.Add : 'T -> bool
Public Function Add (item As T) As Boolean

Parameters

item
T

The element to add to the set.

Returns

true if the element is added to the HashSet object; false if the element is already present.

Implements

Examples

The following example demonstrates how to create and populate two HashSet objects. This example is part of a larger example provided for the UnionWith method.

HashSet evenNumbers = new HashSet();
HashSet oddNumbers = new HashSet();

for (int i = 0; i < 5; i++)
{
    // Populate numbers with just even numbers.
    evenNumbers.Add(i * 2);

    // Populate oddNumbers with just odd numbers.
    oddNumbers.Add((i * 2) + 1);
}
let evenNumbers = HashSet()
let oddNumbers = HashSet()

for i = 0 to 4 do
    // Populate numbers with just even numbers.
    evenNumbers.Add(i * 2) |> ignore

    // Populate oddNumbers with just odd numbers.
    oddNumbers.Add(i * 2 + 1) |> ignore

Remarks

If Count already equals the capacity of the HashSet object, the capacity is automatically adjusted to accommodate the new item.

If Count is less than the capacity of the internal array, this method is an O(1) operation. If the HashSet object must be resized, this method becomes an O(n) operation, where n is Count.

Applies to