I saw Equiso 's comment in one of my answers with an interesting detail, and that is that he implemented an interface (or part of it) without using the operator :
to the right of the object name.
Provided the following code:
public class TestEnumerator
{
private int _veces;
public TestEnumerator(int veces) { _veces = veces; }
public object Current { get { return "Hola " + _veces; } }
public bool MoveNext() { return _veces-- > 0; }
}
public class Test
{
public TestEnumerator GetEnumerator() { return new TestEnumerator(10); }
}
public static void Main()
{
var test = new Test();
foreach (var x in test)
Console.WriteLine(x);
}
Indeed the output is as expected:
Hola 9
Hola 8
Hola 7
Hola 6
Hola 5
Hola 4
Hola 3
Hola 2
Hola 1
Hola 0
Which is equivalent to implementing an IEnumerable<T>
e IEnumerator
in their respective classes. What is this type of implementation called? Since it's a class with an enumerator, but it's not a collection, I'd say it's a half-baked implementation of IEnumerable
.
According to
foreach, in
(C#) :The code you mentioned satisfies the latter case. The method
Reset()
does not necessarily need to be implemented .In fact, a sentence
foreach
of the form: 1is then expanded to:
The variable
e
is not visible or accessible from the original code. The variablev
is read-only in the embedded statement ( embedded-statement ).Grades
Here
Iterators (C# and Visual Basic)
It is mentioned
I understand that he
foreach
is making use ofCurrent
,MoveNext()
andGetEnumerator()
but this is enough for him, it does not validate that this is the interfaceIEnumerable
andIEnumerator
that they are declared, since these still expose the functionality that the iteration needsHow to make a Visual C# class usable in a foreach statement
The correct thing would be to define the interfaces that ensure that the class is iterable