Skip to main content

How to Use the Iterator Pattern in C#

 

How to Use the Iterator Pattern in C#




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 to 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

  • Basic knowledge of OOPs concepts.
  • 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.

public class CarIterator : IVehicleIterator
{
    private List<string> _cars;
    private int _current;
    public CarIterator(List<string> cars)
    {
        _cars = cars;
        _current = 0;
    }
    public string Current()
    {
        return _cars.ElementAt(_current);
    }

    public void First()
    {
        _current = 0;
    }

    public bool IsDone()
    {
        return _current >= _cars.Count;
    }

    public string Next()
    {
        return _cars.ElementAt(_current++);
    }
}


MotorcycleIterator.cs

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

public class MotercycleIterator : IVehicleIterator
{
    private string[] _motercylces;
    private int _current;
    public MotercycleIterator(string[] motercylces)
    {
        _motercylces = motercylces;
        _current = 0;
    }
    public string Current()
    {
        return _motercylces[_current];
    }

    public void First()
    {
        _current = 0;
    }

    public bool IsDone()
    {
        return _current >= _motercylces.Length;
    }

    public string Next()
    {
        return _motercylces[_current++];
    }
}

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.

public class Car : IVehicleAggregate
{
    private List<string> _cars;
    public Car()
    {
        _cars = new List<string> { "Car 1", "Car 2", "Car 3" };
    }

    public IVehicleIterator CreateIterator()
    {
        return new CarIterator(_cars);
    }
}


Motorcycle.cs

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

public class Motercycle : IVehicleAggregate
{

    private string[] _motercycles;
    public Motercycle()
    {
        _motercycles = new[] { "Bike 1", "Bike 2", "Bike 3" };
    }
    public IVehicleIterator CreateIterator()
    {
        return new MotercycleIterator(_motercycles);
    }
}


Iterator Pattern in Action

static void Main(string[] args)
{
    IVehicleAggregate car = new Vehicles.Car();
    IVehicleAggregate motercycle = new Vehicles.Motercycle();

    IVehicleIterator carIterator = car.CreateIterator();
    IVehicleIterator motercycleIterator = motercycle.CreateIterator();

    PrintVehicles(carIterator);
    PrintVehicles(motercycleIterator);
}

static void PrintVehicles(IVehicleIterator iterator)
{
    iterator.First();
    while (!iterator.IsDone())
    {
        Console.WriteLine(iterator.Next());
    }
}

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:



Github Sample Repo

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




Comments

Popular posts from this blog

Organizing Data In Table: A Quick Guide

  Organizing Data In Table: A Quick Guide We can use tables to structure data in columns and rows. The table is the HTML way to lay out the data. The CSS way to create the layout on the web page is  CSS float ,  flexbox , and  CSS grid . We cover an example to understand how to create a table on the web page. You can view the HTML table example at the below codepen link: https://codepen.io/taimoorsattar/pen/NWpdwbp For example, we can create a table in HTML for customer’s grocery item bill as below: < table border = "3" cellpadding = "10" cellspacing = "0" > < caption > Grocery Items Bill </ caption > < thead > < colgroup > < col width = "60%" > < col width = "20%" > < col width = "20%" span = "1" style = "background-color:#f1f1f1;" > </ colgroup > < tr > < th align = ...

5 CSS Tips and Tricks to Try in Your Next Project

  5 CSS Tips and Tricks to Try in Your Next Project Looking for inspiration on how to add a twist to your project design? Take a look at these 5 CSS techniques and have fun experimenting with some bold ideas! 1. Bring back the 90’s with the background-clip Have you ever wondered how to apply a gradient or a texture to the text in CSS? The good news is you can easily achieve that with the background-clip property! First, we need to apply the background color to our  <h1> , then use the value text for the  background-clip  property and set the text color to transparent. < h1 class = "wordart" > The background is clipped to this text </ h1 > h1 { background-color: #ff1493; background-image: linear-gradient(319deg, #ff1493 0%, #0000ff 37%, #ff8c00 100%); } .wordart { -webkit-background-clip: text; color: transparent; } And voilĂ , the 90’ style WordArt is ready! 2. Crazy shapes with clip-path If you like to experiment with your ...

Building A Node.js Based CLI For Real-Time COVID-19 Vaccination Tracking

Why Build? As we already know the whole world is suffering from COVID-19 and the vaccinations are going in full swing everywhere. Finding a slot is getting tougher in our country India as we have a huge population to be vaccinated. Numerous times we have to go to CoWin site to search for a slot and slots are always full. It is pretty time-consuming and irritating. Being a developer, I thought most of the time is usually spent by us in the terminal so why can't we have a basic terminal-based app to save time. So this post will help you in two ways     Learn how to create Node.js based CLI's     Get real-time info about vaccination slots for your area. Let's begin our initial setup! Pre-requisite  – We are assuming you have installed Node.js and npm, If not you can install from  here So as a first step lets initialize our project using command npm init Enter the basic details as shown below. This will create package.json file in the folder cowinCLI. The ne...