Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Use IEnumerator.Reset()?

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 a NotSupportedException.

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?

like image 548
user541686 Avatar asked May 11 '11 18:05

user541686


People also ask

What is the use of IEnumerator?

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".

What is the return type of MoveNext method of IEnumerator?

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false .

What is the difference between IEnumerable and IEnumerator?

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 .

What is IEnumerator interface?

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.


1 Answers

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.

like image 196
Marc Gravell Avatar answered Sep 25 '22 15:09

Marc Gravell