Skip to Content

Set

set<T> is a container that never holds duplicate elements: each distinct value is stored exactly once.

Creation and dedupe

val s: set<string> = ["a", "b", "a"]; print(s, s.Count); s.Add("a"); print(s.Contains("a"), s.Contains("c"), s.Count); s.Remove("b"); print(s);
[a, b] 2 True False 2 [a]

A collection literal is constructed to the target type: three entries written, two survive into the set. Contains decides through hashing, while Remove deletes by value.

An unannotated [1, 2] is inferred as an array by default; to get a set you must annotate set<T> explicitly. The same applies at argument position: when the parameter is set<T>, the caller can write a literal directly.

Set operations

val b: set<int> = [3, 4]; val u: set<int> = [1]; u.UnionWith(b); print(u); val i: set<int> = [1, 3]; i.IntersectWith(b); print(i); val e: set<int> = [1, 3]; e.ExceptWith(b); print(e);
[1, 3, 4] [3] [1]

All four methods modify the receiver in place: UnionWith merges in, IntersectWith keeps the intersection, ExceptWith removes the intersection, and SymmetricExcept(other) swaps in the symmetric difference in place (elements present in exactly one side):

val s: set<int> = [1, 2, 3]; val b: set<int> = [3, 4]; s.SymmetricExcept(b); print(s);
[1, 2, 4]

Relationship tests

val a: set<int> = [1, 2, 3]; val b: set<int> = [3, 4]; print(a.IsSubsetOf(b), a.SetEquals(b));
False False

IsSubsetOf / IsSupersetOf test containment, and SetEquals tests that the elements match exactly. All are read-only checks; neither operand is modified.

Conversion and iteration

val a: set<int> = [1, 2, 3]; val l = a.ToList(); l.Add(9); print(l); for x in a { print("item", x); }
[1, 2, 3, 9] item 1 item 2 item 3

ToList() copies the set into a list; adding and removing afterwards has nothing to do with the set. for-in iterates the elements directly. Iteration order is not guaranteed — call ToList() first when you need a stable order.

Notes

  • Printed form is square brackets, just like a list: [a, b].
  • Set elements have no notion of index; call ToList() first when you need positional access.
  • Elements dedupe and hash under the “equatable” rule; for the equality dichotomy across the language, see equality and hashing.
Last updated on October 11, 2026