Initializing sets

Sets are not terribly commonplace in development, but each of the languages we are examining supports data structures with some form of concrete implementations. Here are some examples of initializing a set, adding a few values to the collection including one duplicate, and printing the set's count to the console after each step.

C#

C# provides a concrete implementation of the set data structure through the HashSet<T> class. Since this class is generic, the caller may define the type used for elements. For example, the following example initializes a new set where the elements will be string types:

 HashSet<string, int> mySet = new HashSet<string>(); mySet.Add("green"); Console.WriteLine("{0}", mySet.Count); mySet.Add("yellow"); ...

Get Everyday Data Structures now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.