V
V
Vadim Nikiforov2022-01-20 16:28:49
C++ / C#
Vadim Nikiforov, 2022-01-20 16:28:49

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

1 answer(s)
V
Vasily Bannikov, 2022-01-20
@nikifovadim

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;
}

Then it will be possible to shove this into the forich:
foreach(int x in new MyEnumerable()) {
  Console.WriteLine(x); // вообще-то мы сюда не попадём, тк Next всегда возвращает false, но синтаксической ошибки нет.
}

Initially, this was invented in order not to cause unnecessary element boxing when iterating over arrays, because initially there were no generics in C# => there was no generic IEnumerable<T>
But now it makes sense to use it only when you want to iterate by ref struct because they cannot implement interfaces.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question