The Set<T> Type

The C# has a number of object types that offer more functionality thatn your standard primitive types. We will look at the List, Set, Dictionary, and File types.

LIst, Set, and Dictionary are known as Generic types (more on this in a further course).

Arrays are limited by their rigidity. You have to create them of a fixed size. You cannot alter their size once they have been created. The only way to access elements is throuh an zero based index.

Represents a strongly typed set of objects that can be accessed by index. It provides methods to search, sort, and manipulate the Set.

You cannot create a Set directly, it must either be a HashSet or a SortedSet.

Example

Result

Example

Result

HashSet<int> setOfAges = new HashSet<int>(); setOfAges.Add(33); setOfAges.Add(56); setOfAges.Add(29); setOfAges.Add(33); foreach (int age in setOfAges) { Console.Write($"{age} "); }

HashSet

Create the Set object and bind it to the int type. The generic class isn’t aware of the type of things it will contain until the time of declaration - line 1. Once the compiler passes this line, all methods on the object that relate to the bound type, are typed against the bound type. E.g. the Add() method’s signature will be void Add(int element).

The Add() method adds an item to the Set. Items of the same value are not added to the collection.

In the foreach satement, each item in setOfAges is projected one by one into the age variable. Each time a value from setOfAges is projected into age the code block is executed with the current value in age. This repeats until all items within setOfAges have been exhausted.

33 56 29

will be printed

SortedSet<int> setOfAges = new SortedSet<int>(); setOfAges.Add(29); setOfAges.Add(56); setOfAges.Add(33); foreach (int age in setOfAges) { Console.Write($"{age} "); }

SortedSet

Create the Set object and bind it to the int type.

The SortedSet will sort items as they are added to the collection

29 33 56

Will be printed

 

Â