C# Design Pattern – Iterator

According to Gang of Four, the iterator pattern provides a process to obtain the aggregator object without knowing its implementation.

Use Case

Let us take an example of a collection list of cars and string[] an array of motorcycles, we need to design an aggregator object so that one can iterate over the collection without knowing whether it’s a list or an array.

The iterator design pattern helps solve this problem wherein a standard iterator will traverse different collection types.


Prerequisites

  1. Basic knowledge of OOPS concepts.

  2. Any programming language knowledge.

The article demonstrates the usage of iterator design patterns using the C# programming language.




Getting Started

Considering the above use case, let us define a custom iterator interface that acts as an abstract layer over the list and array iterator.

public interface IVehicleIterator{
  void First();
  bool IsDone();
  string Next();
  string Current();
}

Now write car and motorcycle iterators that implement the above interface according to the use case.


CarIterator.cs

The car iterator is implemented over List<string> collection and provides an implementation of interface methods.

MotorcycleIterator.cs

The motorcycle iterator is implemented over string[] collection and provides an implementation of interface methods.


After all the above iterators are defined, define a standard aggregator object interface that creates iterators.

public interface IVehicleAggregate{
   IVehicleIterator CreateIterator();
}

Finally, write down the classes which implement the above aggregator interface. According to the use-case, both Car and Motorcycle classes will implement the aggregator interface.




Car.cs

The method of aggregator interface returns the relevant iterator as shown below.

Motorcycle.cs

The method of aggregator interface returns the relevant iterator as shown below.


Iterator Pattern in Action

The PrintVehicles methods check if !iterator.isDone then output the collection element. No matter what collection we’re dealing with, implement methods like First, IsDone, and Next.

Output

We don’t know the underlying collection type, but it is still iterated over it via Iterator Design Pattern. If you go ahead and run, it displays the following output.




Thank you for reading, and I hope you liked the article. Please provide your feedback in the comment section.


Follow me on

C# Publication, LinkedIn, Instagram, Twitter, Dev.to, Pinterest, Substack, Wix.


Tags: #IteratorPattern #Csharp #DotnetCore #DesignPatterns #Dotnet

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w