using System.Collections.Generic; HashSetIn this example, we create a HashSet of integers and add some elements to it. Then, we try to add an element that already exists in the HashSet (2), and one that doesn't exist (3). The AddIfNotExists method only adds the 3 to the HashSet, leaving the 2 unchanged. The package library for the HashSet is part of the .NET Core Class Library, which is included in the standard .NET installation.
numbers = new HashSet (); numbers.Add(1); numbers.Add(2); numbers.AddIfNotExists(2); // This element already exists, so it won't be added numbers.AddIfNotExists(3); // This element doesn't exist, so it will be added