In C#, HashSet.GetEnumerator() gives you an enumerator: a small helper object that walks through the set one item at a time. You ask it MoveNext() to go to the next item, and read the current item from Current.
Most of the time you will not call it yourself. A foreach loop calls GetEnumerator() for you behind the scenes. The return type is HashSet<T>.Enumerator, a struct (a value type), so avoid copying it around. The order of items is not promised, so never write code that depends on it.
This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.GetEnumerator(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order.
Syntax
Use foreach in normal code. Call GetEnumerator directly only when you need manual control.
C#
HashSet<int> numbers = new HashSet<int> { 10, 20, 30 };
foreach (int n in numbers) { // GetEnumerator() is called for you
Console.WriteLine(n);
}
using (HashSet<int>.Enumerator e = numbers.GetEnumerator()) {
while (e.MoveNext()) {
int current = e.Current;
}
}
Call
What it does
foreach (int n in numbers) { ... }
The everyday way. The compiler calls GetEnumerator(), MoveNext(), Current, and Dispose() for you.
numbers.GetEnumerator()
Returns a HashSet<T>.Enumerator struct. Wrap it in using so it is disposed.
e.MoveNext()
Moves to the next item. Returns false when there are no more items.
Do not change the set (for example with Add) while you loop over it. The enumerator notices the change and the next step throws InvalidOperationException. Newer .NET versions allow Remove during a loop, but older ones do not, so the safe habit is to use RemoveWhere().
Library declarations
C#
public HashSet<T>.Enumerator GetEnumerator();
Parameters
Parameter
Description
None
GetEnumerator() takes no parameters.
Return Value
Return Value
Description
HashSet<T>.Enumerator
A struct enumerator that visits every item once. Use MoveNext() and Current. The order is not promised.
C# Examples
Example 1 — Loop With foreach and Use Order-Free Results
Walk through a set with foreach and compute things that do not depend on order: a total and a count.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> numbers = new HashSet<int> { 10, 20, 30 };
int total = 0;
int big = 0;
foreach (int n in numbers) {
total += n;
if (n > 15) {
big++;
}
}
Console.WriteLine(total);
Console.WriteLine(big);
Console.WriteLine(numbers.Count);
}
}
Output
60
2
3
How It Works
foreach calls GetEnumerator. You never type the call. The compiler asks the set for its enumerator and loops until MoveNext() says there are no more items.
Order may vary. The loop may visit 10, 20, and 30 in any order, so the program avoids printing inside the loop.
Order-free answers. A sum and a count give the same result whatever the visiting order: the total is 60, and two items (20 and 30) are bigger than 15.
Set unchanged. Reading changes nothing, so Count is still 3.
Example 2 — Use the Enumerator by Hand
Call GetEnumerator yourself, step with MoveNext, read Current, and see what happens after the last item.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> numbers = new HashSet<int> { 10, 20, 30 };
int steps = 0;
int total = 0;
using (HashSet<int>.Enumerator e = numbers.GetEnumerator()) {
while (e.MoveNext()) {
steps++;
total += e.Current;
}
Console.WriteLine(e.MoveNext());
}
Console.WriteLine(steps);
Console.WriteLine(total);
}
}
Output
False
3
60
How It Works
Enumerator is a struct. The type HashSet<int>.Enumerator is a value type. Keep it in one variable and do not pass copies around, or the copies each have their own position.
MoveNext drives the loop. It returns true while there is another item and moves Current to it. The while loop runs three times.
After the end. When the items run out, MoveNext() returns False, which the first printed line shows. Do not read Current after that.
using disposes it. The using block calls Dispose() at the end, just like a foreach does. Then steps is 3 and total is 60.
Example 3 — Adding During a Loop vs RemoveWhere
Add an item inside a foreach over the same set, catch the error, then use RemoveWhere as the safe way to delete.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> numbers = new HashSet<int> { 1, 2, 3 };
try {
foreach (int n in numbers) {
numbers.Add(n + 10);
}
} catch (InvalidOperationException) {
Console.WriteLine("Collection was modified");
}
Console.WriteLine(numbers.Count);
Console.WriteLine(numbers.RemoveWhere(n => n > 10));
Console.WriteLine(numbers.Count);
}
}
Output
Collection was modified
4
1
3
How It Works
Changing the set in the loop. The body calls numbers.Add on the very set being walked. The first item always adds a new value, because 11, 12, and 13 are not in the set yet.
The enumerator notices. On the next MoveNext() the enumerator sees the set changed and throws InvalidOperationException. The catch block prints a message.
Exactly one add happened. The loop stopped after one item, so the set grew from 3 to 4 items.
The safe way.RemoveWhere(n => n > 10) does the looping inside the set, so there is no enumerator to break. It removes the 1 added item, and Count is back to 3.
Frequently Asked Questions
It returns a HashSet<T>.Enumerator, which is a struct that visits each item once. You use MoveNext to step forward and Current to read the item.
Almost never. A foreach loop calls it for you. Call it directly only when you need manual control of the loop.
The order is not promised. It can differ from the order you added items in, and it may change after adds and removes. Sort a copy when you need a fixed order.
You changed the set (for example with Add) while looping over it. Collect the changes and apply them after the loop, or use RemoveWhere to delete by a rule.
A struct avoids creating an extra object for every loop, which is faster. The downside is that copies each have their own position, so keep it in a single variable.