What's the point in implementing Reset() method of IEnumerator?


P

Pavils Jurjans

Hello, please consider the code at the end of this posting, that depicts
simple case of custom enumerator. This particular example will enumerate
over list of random number within 1..10, and will stop once the value of 10
is reached. My question, is what's the real point of implemending the
Reset() method, if it is never used by foreach statement. Of course, it
gives me some allocated place where I can do some "enumerator resetting" and
call the Reset() method from the enumerator constructor, but it's somewhat
strange that the IEnumerator interface demands Reset() to be present, but
never actually cares to call it.

-- Pavils


using System;
using System.Collections;

/*<Settings>
<Outfile>temp</Outfile>
<Run/>
</Settings>*/

class EnumTest : IEnumerable
{
class EnumTestEnumerator : IEnumerator
{
private int rndValue;
private static Random rnd = new Random();
public object Current
{
get
{
Console.WriteLine("Current");
rndValue = rnd.Next(1, 11);
return rndValue;
}
}
public bool MoveNext()
{
Console.WriteLine("MoveNext()");
return rndValue == 0 || rndValue != 10;
}
public void Reset()
{
Console.WriteLine("Reset()");
}
}
public IEnumerator GetEnumerator()
{
return new EnumTestEnumerator();
}
}

class Tester
{
public static void Main()
{
EnumTest et = new EnumTest();
foreach (int value in et)
{
Console.WriteLine(value);
}
Console.Read();
}
}
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

Pavils Jurjans said:
Hello, please consider the code at the end of this posting, that depicts
simple case of custom enumerator. This particular example will enumerate
over list of random number within 1..10, and will stop once the value of 10
is reached. My question, is what's the real point of implemending the
Reset() method, if it is never used by foreach statement.

The point is that IEnumerator isn't only used by foreach - anyone can
use it.
Of course, it
gives me some allocated place where I can do some "enumerator resetting" and
call the Reset() method from the enumerator constructor, but it's somewhat
strange that the IEnumerator interface demands Reset() to be present, but
never actually cares to call it.

It's up to the client to call it. If you know that you'll never call
it, don't bother implementing it fully - throw a NotSupportedException,
for instance.
 
Ad

Advertisements

P

Pavils Jurjans

Hallo Jon,
The point is that IEnumerator isn't only used by foreach - anyone can
use it.

Can you name some case, when it's used within default .NET framework
classes? That would help to understand better why the enumerator object is
being reused, not instantiated as new.

-- Pavils
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top