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

Detecting The User's Color Scheme Preference With CSS

Detecting The User's Color Scheme Preference With CSS If you’re a developer, chances are that you use dark mode on your machine and code editor. If not, what are you waiting for? Join the dark side! Jokes apart, it is common nowadays to allow users to select a different theme when visiting a website. Now you can do this with CSS only, not the theme selection itself, for that you still need JS but with CSS you can now detect the user’s machine color scheme (light or dark) and display the correct colors on your website immediately. To do this we need to use the CSS variables. According to the website  Can I use , the “CSS variables” feature is available on 95% of the currently used browsers around the world. We also need to use the  prefers-color-scheme  media query, which according to  Can I use  is supported by about 90% of the currently used browsers. In this article, I will show you how to use the CSS variables and the  prefers-color-scheme  to setup the default colors of the web

Top 10 Python Frameworks Ranked on Github

  Top 10 Python Frameworks Ranked on Github A framework is a library that makes building web applications easier. Frameworks provide a structure for developers so they can focus more on the business logic of their applications. Python has one of the largest ecosystems with a great number of different libraries, frameworks, and tools for developers. Let's take a look at the best Python  frameworks for web development . Here is a list of the ten highest-ranked Python frameworks  on GitHub. Django    Django is an open-source framework that makes things very fast and scalable. It enables programmers to develop apps and websites of different complexity within a short time. Django's advantages are reusability of components, less code, low coupling, and a principle of not repeating. Moreover, the framework is easy to use. You don't need special tools to develop a Django project. You can write it in a typical text editor, such as notepad. In this way, Django is easy to learn for be

1.Change windows password without knowing the existing password

We all know that to change password in windows we need to enter the existing password and then we can proceed to enter the new password.However there is a trick to change password without knowing the existing password. This trick comes handy when the system is logged in and we have forgotten the password or to pull a prank on your friend(do it at your own risk) Step 1: Right click on computer and select manage Step 2: click on Local users and Groups and click on users. On the right pane you will see list of users. step 3: Right click on any user whose password you want to change and click on set password: step 4: click on proceed(Don’t worry about the message) step 5: Enter the new password step 6: Click on ok and your password will change. You can even use the same method to change HOMEGROUP password. (NOTE: This trick works on WIN 7, 8 , 8.1 ,10)