Answer the question
In order to leave comments, you need to log in
Using foreach iterators?
Hello everyone, the essence of the question:
there is a Foreach loop that actually iterates an object, how to understand why and when to use interfaces with their GetEnumerator () method; IEnumerable, IEnumerator, IEnumerable and IEnumerator
and what is the actual difference between using these interfaces with a loop? why can't I just use a loop without resorting to them ?
Answer the question
In order to leave comments, you need to log in
Interfaces are needed so that other classes can work with your own classes.
For example, you have implemented your own collection of objects with your own strange logic. Let's say you want this collection to be iterable with a foreach loop, but initially the framework has no idea how to iterate through the objects within your collection. That's when you declare that your class implements the IEnumerable interface and exposes the implementation of that interface to the outside. That's when the framework already knows how to iterate over all the elements of the collection.
IEnumerable implements both an array and a list and a dictionary and a linked list, that is, in order for you to be able to walk through any class using foreach, this class must implement IEnumerable. Think of an interface as a "collaboration agreement" between different classes that clearly defines the rules for interaction.
There shouldn't be duck typing in a strongly typed language.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question