IEnumerator in C#

In yesterday’s post I mentioned the IEnumerator interface. To be honest it probably was not the best example to cite for an interface, since it is implemented in a non-standard fashion. However, it’s also the interface you will probably want to implement the most often, so I thought it worth showing you a quick example.

For today’s lesson I will continue to use the Employee example I’ve shown over the last few days. The only change I need to make is to the Employee’s class declaration, for easy coding I want it to have a public scope. In looking back I hadn’t put a scope qualifier on the class declaration, and when you omit a scope the compiler defaults to internal.

  public class Employee : IPersonM, IPersonP

 

Now that’s done, let’s create a class that will hold multiple employees. We’ll call it Employees (plural) and have a method to add employees to it. Internally we’ll store the individual Employee objects in a generic List<T> collection.

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  public class Employees

  {

    private List<Employee> _employees = new List<Employee>();

 

    public void AddEmployee(Employee emp)

    {

      _employees.Add(emp);

    }

 

    public IEnumerator<Employee> GetEnumerator()

    {

      foreach (Employee emp in _employees)

      {

        yield return emp;

      }

    }

 

  }

}

 

Before I explain the details, let’s look at how to use the new collection.

 

      Employees myEmployees = new Employees();

 

      Employee emp1 = new Employee();

      emp1.FirstName = “Carl”;

      emp1.Lastname = “Franklin”;

      myEmployees.AddEmployee(emp1);

 

      Employee emp2 = new Employee();

      emp2.FirstName = “Richard”;

      emp2.Lastname = “Campbell”;

      myEmployees.AddEmployee(emp2);

 

      Employee emp3 = new Employee();

      emp3.FirstName = “Mark”;

      emp3.Lastname = “Miller”;

      myEmployees.AddEmployee(emp3);

 

      string everyone = “”;

      foreach (Employee emp in myEmployees)

      {

        everyone += (emp.FullName() + Environment.NewLine);

      }

 

      MessageBox.Show(everyone, “Everyone”);

 

As you can see this is pretty straight forward, it created 3 employee objects and called the AddEmployee method to add them to our collection. The code then enters a foreach loop retrieving each individual Employee object from the collection of Employees.

What makes this work is the IEnumerator interface. By having the Employees class have a GetEnumerator method that returns an IEnumerator, we enable it to be used anywhere that an IEnumerator can be used, such as a foreach loop.

The only other thing to explain would be the new keyword yield. Each time through the loop the yield will exit the loop and return to the calling routine. The next time through the foreach loop, the GetEnumerator picks right back up at the yield statement, and loops to the next item in our internal List.

To your method, he yield keyword is sort of like sleep mode is to the computer. It pauses, then returns control to the calling routine. When you return, you re-enter the routine right where you left off, with all the routines and variables just as you left them. Not unlike powering up your computer again from sleep mode.

What makes this a little different is that the method GetEnumerator is what implements the IEnumerator interface. Normally, interfaces are implemented by the entire class, not just a single method.

While not the best example of a standard interface, it does demonstrate the power of extending an existing .Net interface. In this example it suddenly allowed your class to be used by a foreach loop. Take advantage of the built in .Net interfaces to make your own classes even more powerful and fit into the .Net environment.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s