Hashset<T> is unordered collection. Because HashSet<T> does not contain keys and is unordered,  collection has to be enumerated to find element. HashSet is used because it is very fast collection and because HashSet guarantees uniqueness of elements.

Declaration

HashSet<T> can can contain reference or value types. We declare it by typing HashSet followed by<> (angle brackets) and inside <> should be our type and after that should be variable name:

Initialization

As HashSet<T>  is an reference type so we initialize it by assigning HashSet variable to HashSet instance. HashSet type should be specified while instantiating HashSet<T>.

Populating a HashSet <T>

Using collection initialzier

Using Add method

Add method returns bool value so Add method can also be used to detect if value already exists inside HashSet.

No exception will be thrown if string Zadar exist and Tokyo string will be added to the collection. Also note that if you try to add string LONDON (with uppercase letters) that value will be added so make sure that you check yourself for uppercase scenario or use StringComparer like this:

Remove an element from the HashSet<T> using Remove method

How to use HashSet<T>

Iterate through HashSet<T>

We can iterate an HashSet<T> using for and foraech statements. Using these loops elements will not be poped from the HashSet.

foreach (var cityName in cityNames)

{

     Console.WriteLine(cityName);

 }

for (int i = 0; i < cityNames.Count; i++)

{

    var city = cityNames.ElementAt(i);

    Console.WriteLine(city);

}

Number of elements inside of a HashSet<T>

int setCount = cityNames.Count;