Iterator is a common design pattern. It is usually used in a situation when you want to iterate a collection but do not want to expose the collection detail. The following is the classical iterator pattern.
Making an iterator is a tedious thing. Due to an iterator is very practical and common, as a software engineer. We should implement in library so that everybody can use it directly. In c#, this pattern has implemented already. It is in “IEnumerator” interface.
Let’s see the definition of List class.
From the above source code. We know that list class implements “IEnumerable” interface. Inside “IEnumerable”, there is a function called “GetEnumerator” and the return object type is “IEnumerator”.
It’s because list class implements “IEnumerable” interface, thus list class can use foreach loop to iterate each object inside the container. In the following example, I show you how to implement it by yourself. I create a MessageBox collection to store all Message Objects.
Example
Message
MessageBox
At this time, MessageBox has not implements an “IEnumerable interface”. Therefore, there is a compile error if you use foreach statement to iterate the message object.
However, once "MessageBox" implements the “IEnumerable” interface, the compile error disappears.
Finally, I implement the detail of iteration in “GetEnumerator” function in "MessageBox". Then, the "MessagBox" can iterate all message objects.
You can consider the meaning of yield is “return first then execute after” Therefore, the execution sequence is “Before yield”, Msg content and “After Yield”.
Summary
Implement the “IEnumerable” interface in custom collection class can make you code more concise, get the advantage of iterator pattern easily and reduce the development time. Therefore, I recommend you to implement “IEnumerable” interface in your custom collection.
The source code of this article I post it on my github https://github.com/Isaac234517/C-_IteratorEample
Thank you!
Please leave your email below.