C# HashSet<T>

C# HashSet class can be used to store, remove or view elements. It does not store duplicate elements. It is suggested to use HashSet class if you have to store only unique elements. It is found in System.Collections.Generic namespace.

C# HashSet<T> example

Let's see an example of generic HashSet<T> class that stores elements using Add() method and iterates elements using for-each loop.

Output:

Sonoo
Ankit
Peter
Irfan

C# HashSet<T> example 2

Let's see another example of generic HashSet<T> class that stores elements using Collection initializer.

Output:

Sonoo
Ankit
Peter
Irfan
Next TopicC# SortedSet




Latest Courses