How exactly is the right way to call IEnumerator.Reset
?
The documentation says:
The
Reset
method is provided for COM interoperability. It does not necessarily need to be implemented; instead, the implementer can simply throw aNotSupportedException
.
Okay, so does that mean I'm not supposed to ever call it?
It's so tempting to use exceptions for flow control:
using (enumerator = GetSomeExpensiveEnumerator()) { while (enumerator.MoveNext()) { ... } try { enumerator.Reset(); } //Try an inexpensive method catch (NotSupportedException) { enumerator = GetSomeExpensiveEnumerator(); } //Fine, get another one while (enumerator.MoveNext()) { ... } }
Is that how we're supposed to use it? Or are we not meant to use it from managed code at all?
Here is the documentation on IEnumerator . They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate , which means "to count off or name one by one".
If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false .
An IEnumerator is a thing that can enumerate: it has the Current property and the MoveNext and Reset methods (which in . NET code you probably won't call explicitly, though you could). An IEnumerable is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator .
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement. IEnumerator has two methods MoveNext and Reset. It also has a property called Current.
never; ultimately this was a mistake. The correct way to iterate a sequence more than once is to call .GetEnumerator()
again - i.e. use foreach
again. If your data is non-repeatable (or expensive to repeat), buffer it via .ToList()
or similar.
It is a formal requirement in the language spec that iterator blocks throw exceptions for this method. As such, you cannot rely on it working. Ever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With