skip to content

In C#, what do HashSet<T>'s UnionWith, IntersectWith and ExceptWith do to the set you call them on, and how do SetEquals and IsSubsetOf compare?

level: middleimportance: should knowfreq 45%

answer

  1. look at the return type
  2. the receiver changes
  3. copy before you combine
  4. order and duplicates in the argument

basics

~20 s

UnionWith, IntersectWith and ExceptWith mutate the HashSet<T> they are called on and return void, so copy the set first if you still need it. SetEquals and IsSubsetOf only test, ignoring order and duplicates in the other collection.

solid answer

~30 s

`HashSet<T>` exposes set algebra as in-place methods: `UnionWith(other)` adds every element of `other`, `IntersectWith(other)` keeps only elements also in `other`, `ExceptWith(other)` removes elements found in `other`, and `SymmetricExceptWith` keeps elements in exactly one of the two. They return `void` and change the receiver, so `today.IntersectWith(yesterday)` destroys today's scan list; write `var both = new HashSet<WarehouseBin>(today); both.IntersectWith(yesterday);` instead. `SetEquals`, `IsSubsetOf`, `IsSupersetOf`, `IsProperSubsetOf` and `Overlaps` return `bool` and change nothing; they accept any `IEnumerable<T>`, ignore its order and duplicates, and judge membership with the receiving set's comparer. `Add` returns `false` for an element already present.

code

csharp · 27 lines
csharp
var today = new HashSet<WarehouseBin> { new("A", 1, 4), new("B", 2, 1), new("C", 3, 7) };
var yesterday = new HashSet<WarehouseBin> { new("B", 2, 1), new("C", 3, 7), new("D", 4, 2) };

var both = new HashSet<WarehouseBin>(today);   // copy first: the *With methods mutate the receiver
both.IntersectWith(yesterday);
Print("both days", both);

var newToday = new HashSet<WarehouseBin>(today);
newToday.ExceptWith(yesterday);
Print("new today", newToday);

var either = new HashSet<WarehouseBin>(today);
either.UnionWith(yesterday);
Print("either day", either);

Console.WriteLine(today.Count);                                    // 3: untouched
Console.WriteLine(both.IsSubsetOf(today));                         // True
Console.WriteLine(today.SetEquals([new("C", 3, 7), new("A", 1, 4), new("B", 2, 1), new("A", 1, 4)])); // True
Console.WriteLine(today.Add(new WarehouseBin("A", 1, 4)));        // False

today.IntersectWith(yesterday);                                    // the bug: today's own scans are gone
Console.WriteLine(today.Count);                                    // 2

static void Print(string label, HashSet<WarehouseBin> set) =>
    Console.WriteLine($"{label}: {string.Join(", ", set.Select(b => $"{b.Aisle}-{b.Shelf}-{b.Slot}").Order())}");

readonly record struct WarehouseBin(string Aisle, int Shelf, int Slot);

go deeper

for a junior

Recall that HashSet<T> keeps unique elements, that Add returns false for a duplicate, and that UnionWith, IntersectWith and ExceptWith change the set they are called on.

for a middle

Explain the void-returning mutation methods against the bool-returning comparisons, why you copy before combining, and how the argument's order and duplicates are ignored.

for a senior

Spot the shared-set bug in review, where a set passed around the code is intersected in place, and choose between a copy plus IntersectWith and LINQ's non-mutating operators.

for a principal

Ask whether a shared set should be exposed as a mutable HashSet<T> at all, since any holder can rewrite it with one call; handing out a read-only interface hides the mutation methods from casual callers.

## Two families of methods `HashSet<T>` is .NET's hashed collection of unique elements. Beyond `Add`, `Remove` and `Contains`, it implements the `ISet<T>` operations in two families that are easy to tell apart by return type: | Method | Effect on the receiver | Returns | |---|---|---| | `UnionWith(other)` | adds every element of `other` | `void` | | `IntersectWith(other)` | keeps only elements also in `other` | `void` | | `ExceptWith(other)` | removes every element found in `other` | `void` | | `SymmetricExceptWith(other)` | keeps elements in exactly one of the two | `void` | | `SetEquals(other)` | none | `bool` | | `IsSubsetOf` / `IsSupersetOf` | none | `bool` | | `IsProperSubsetOf` / `IsProperSupersetOf` | none | `bool` | | `Overlaps(other)` | none | `bool` | Every `other` parameter is an `IEnumerable<T>`, so the argument can be another set, a `List<T>`, an array or a query. ## The mutation trap The `...With` methods are **in place**. There is no returned set to assign; the set you call them on becomes the result. In a warehouse service that keeps `today` and `yesterday` as `HashSet<WarehouseBin>`: 1. `today.IntersectWith(yesterday)` leaves `today` holding only the bins scanned on both days. Bins scanned only today are gone. 2. Any later code that reads `today` to list today's scans now gets the wrong answer, and nothing throws. 3. The fix is to copy first: `var both = new HashSet<WarehouseBin>(today); both.IntersectWith(yesterday);`. The copy does not inherit the source's comparer: `new HashSet<T>(today)` uses the default one, so pass `today.Comparer` as the second argument when `today` was built with a custom comparer. The same applies to `ExceptWith` (bins new today) and `UnionWith` (bins scanned on either day). `SymmetricExceptWith` answers "scanned on exactly one of the two days" in one call. ## How the comparisons treat the other collection - **Order is ignored.** `SetEquals` asks whether both contain the same distinct elements. - **Duplicates are ignored.** `new HashSet<int> {1, 2}.SetEquals(new List<int> {2, 1, 1})` returns `true`; the list is read as the set {1, 2}. - **The receiver's comparer decides.** Membership is tested with the comparer of the set you call the method on. When `other` is also a `HashSet<T>` with an equal comparer, the methods take faster paths, for example `SetEquals` returning `false` immediately when the counts differ. - **Empty sets behave mathematically.** An empty set is a subset of anything, and `IntersectWith` an empty collection clears the receiver. ## What each operation costs The methods are written to touch each element a small number of times: - `UnionWith` and `ExceptWith` simply call `Add` or `Remove` for every element of `other`, so they cost one lookup per element of the argument. - `IntersectWith` with another `HashSet<T>` sharing the comparer walks the receiver and removes whatever the other set lacks. With any other argument it walks `other`, marks which of its own slots were seen in a bit array (stack-allocated when the set is small), then removes every unmarked element. - The comparison methods stop early where they can, for example `SetEquals` with a same-comparer set returns `false` at once when the counts differ, and `IsSubsetOf` returns `true` immediately for an empty receiver. ## HashSet methods compared with LINQ operators LINQ's `Union`, `Intersect` and `Except` produce the same memberships without touching either input. They return a lazily evaluated sequence that builds its own internal set when enumerated, which suits a one-off pass over two sources you must keep unchanged. The in-place methods suit code that wants the result as a `HashSet<T>` anyway and can afford to mutate a copy. How LINQ defers that work is covered with LINQ. ## Other members worth knowing - `Add(item)` returns `bool`: `true` when the element was added, `false` when an equal element was already present. It never throws for a duplicate, which makes `if (!seen.Add(bin))` a one-lookup duplicate check. - `RemoveWhere(Predicate<T>)` removes every matching element and returns the count removed. - `TryGetValue(equalValue, out actualValue)` returns the instance actually stored, useful when equal elements are different objects. - Enumeration order of a `HashSet<T>` is not promised, so sort the elements before you print or compare them as a sequence.

  • Why does IsSubsetOf give the right answer when the argument is a List<T> with duplicates?
    It treats the argument as a set: it counts how many distinct elements of the receiver appear in the list, using the receiver's comparer, and ignores repeats and order. `new HashSet<int> {1, 2}.IsSubsetOf(new List<int> {2, 2, 1, 5})` returns `true`.
  • When would you choose LINQ's Intersect over HashSet<T>.IntersectWith?
    When both inputs must stay unchanged and you only need to walk the result once, for example to stream it to a report. `Intersect` leaves the sources alone and yields lazily. `IntersectWith` is the better fit when you want a `HashSet<T>` as the result and can mutate a copy you own.
  • What does SymmetricExceptWith give the warehouse service?
    The bins scanned on exactly one of the two days, newly scanned bins plus bins that dropped out, in one in-place call. Run it on a copy of `today` with `yesterday` as the argument so that `today` itself survives.

The ...With methods are a red pen on your only copy of a guest list: after crossing out everyone who did not attend, the original list no longer exists. Photocopy it first if anyone still needs it.

  • IntersectWith returns a new HashSet<T> and leaves the original unchanged.
  • SetEquals returns false when the other list holds the same items in another order.
  • HashSet<T>.Add throws an exception when the element is already present.
  • IsSubsetOf only accepts another HashSet<T> as its argument.
  • HashSet<T> guarantees enumeration in insertion order.