Answer the question
In order to leave comments, you need to log in
What is Duck typing and when can we foreach iterate through our own collection?
When can we iterate through our own collection with foreach?
What needs to be done for this and why? (Tell about duck typing)
Answer the question
In order to leave comments, you need to log in
As I understand it, the question is about the fact that it is absolutely not necessary to implement IEnumerable to pass through the collection through foreach - it is enough to write a couple of methods:
public class MyEnumerable {
public MyEnumerator GetEnumerator() => new MyEnumerator();
}
public class MyEnumerator {
// Этот метод должен переходить к следующему элементу, и возвращать true, если переход произошёл,
// и false, если дальше элементов нет
public bool MoveNext() => false;
// Это свойство должно возвращать текущий элемент
public int Current => 0;
}
foreach(int x in new MyEnumerable()) {
Console.WriteLine(x); // вообще-то мы сюда не попадём, тк Next всегда возвращает false, но синтаксической ошибки нет.
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question