Microsoft & .NETVisual C#Managed Extensions: Combining IEnumerable and IEnumerator

Managed Extensions: Combining IEnumerable and IEnumerator

Welcome to this week’s installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer demonstrates how to perform a practical .NET programming task using either C# or Managed C++ Extensions.

Previous installments of the .NET Tips & Techniques series covered using types defined in the .NET Collection namespace to make classes both enumerable and sortable from Visual C++ and Managed Extensions applications. Each article employed the technique of creating two additional classes to the class being enumerated: a collection class (IEnumerable-derived) and an enumerator class (IEnumerator-derived). This article explains why the .NET BCL (Base Class Library) team chose to define two interfaces that are used together to achieve enumerability and how—in specific scenarios—you can define a single class that implements both interfaces.

Why Two Interfaces?

Why doesn’t the IEnumerable interface define the Current, MoveNext, and Reset members, thereby eliminating the need for the
IEnumerable::GetEnumerator method and the IEnumerator interface? That way, the collection class could simply provide public accessor methods to the data.
Although this technique sounds reasonable at first blush, it has drawbacks.

One such drawback is evident if a single collection object can have multiple clients and its data can be modified (especially if records can be added or deleted) while the data is being enumerated. You could, of course, circumvent this particular problem by creating a “data object” internal to the collection object for each client. Then the problem would be associating each client with its respective data object—typically done through an attach/detach method pair. The client then would need to identify itself using some sort of ID (probably returned from an attach method) in order to retrieve its data.

As you can see, this solution heads down a slippery slope of diminishing returns, generating more work than it alleviates. This is not even mentioning the fact that you would forfeit the generic solution afforded you via the IEnumerable/IEnumerator interface pair. With these interfaces, the snapshot of the collection data that existed when the client requested the enumerator object is copied to the enumerator object and becomes available via the standard methods: Current, MoveNext, and Reset.

Combining the Two Interfaces

Having two distinct interfaces (IEnumerable and IEnumerator) eases the burden of keeping track of enumerators that represent snapshots of dynamic data. The logical question then is “what if the data is static?” In other words, why define an enumerator class that has its own copy of the original collection data if that data never changes? This is one scenario where combining the two interfaces into a single collection class would be advantageous. (You could also keep the collection and enumerator class definitions separate and simply not copy the data—instead having the enumerator object’s Current, MoveNext, and Reset members directly access the collections data. However, why even define a separate enumerator class in situations where it has no benefit?)

Therefore, in the following class definitions, I’ve taken the Article class used in the past few articles and modified it to include a single class (ArticleCollection) that implements both the IEnumerable and IEnumerator interfaces:

#pragma once

#pragma push_macro("new")
#undef new

__gc class Article
  Article(String* title, String* author, String* category)
    this->title = title;
    this->author = author;
    this->category = category;

  String* title;
  String* author;
  String* category;

  __property String* get_Title() { return this->title; }
  __property String* get_Author() { return this->author; }
  __property String* get_Category() { return this->category; }

__gc class ArticleCollection : public IEnumerable, public IEnumerator
  ArrayList* articles;
    articles = new ArrayList();
    // create some sample data
    articles->Add(new Article(S"Article #1", 
                              S"Managed Extensions"));
    articles->Add(new Article(S"Article #2", 
                              S"Visual C++/MFC"));
    articles->Add(new Article(S"Article #3", 
  IEnumerator* GetEnumerator()
    return this;

  int position;

  bool MoveNext() { return (++position < articles->Count); }

  __property Object* get_Current()
    if (0 > position
    || position >= articles->Count)
	    throw new InvalidOperationException();

    return articles->Item[position];

  void Reset() { position = -1; }
#pragma pop_macro("new")

Here’s a list of the main changes to the technique for enumerating your classes covered in the article, Managed Extensions: Adding Enumeration to Your Classes:

  • Aside from the class you want enumerable, the only class you need to add is a collection class that implements (derives from) both IEnumerable and IEnumerator. In this example, this leaves you with the Article and ArticleCollection classes.
  • Since the collection class implements both interfaces, the GetEnumerator method can now simply return the current object instance instead of instantiating a separate enumerator object, which would involve the unnecessary copying of the collection object’s data.
  • The Reset, MoveNext, and get_Current methods are now in the collection class.

About the Author

The founder of the Archer Consulting Group (ACG), Tom Archer has been the project lead on three award-winning applications and is a best-selling author of 10 programming books as well as countless magazine and online articles.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories