September 1, 2015
Hot Topics:

Managed Extensions: Adding Enumeration to Your Classes

  • August 23, 2004
  • By Tom Archer
  • Send Email »
  • More Articles »

The Client Side

Now that the Article class is enumerable, look at how client code enumerates a collection of Article objects. Assuming you instantiated and filled an object of type ArticleCollection, you could code a C++ client as follows:
Type* t = __typeof(ArticleCollection);
if (t->GetInterface(S"IEnumerable"))
  // m_articles is a class-level object of type ArticleCollection
  IEnumerator* en = m_articles->GetEnumerator();
  while (en->MoveNext())
    Article* article = dynamic_cast(en->Current);
    // Access the article object members as needed
In C#, the client would look like the following:
if (m_articles is IEnumerable)
  foreach(Article article in m_articles)
As you can see, C# supports a couple of keywords that reduce the typing a bit, but they both work basically the same.

C# Clients and the foreach Operator

While this article specifically covers how to provide enumeration for your classes using Managed Extensions, you should always take care to accommodate the idiosyncrasies of other .NET languages&#mdash;especially the more popular languages. To that extent, C# programmers expect to be able to use the foreach operator in enumerating collections. This operator can be used only on expressions that are collection types. As defined in the .NET documentation, a collection type is one that either implements the IEnumerable interface (as you've done here) or implements the collection pattern, which is defined as follows:
  • The expression variable must contain a public instance method named GetEnumerator that takes no parameters and returns a struct, class, or interface.
  • The type returned from the GetEnumerator method must contain a public instance method named MoveNext that takes no parameters and returns a bool.
  • The type returned from the GetEnumerator method must contain a public instance method named Current that takes no parameters and returns a reference type.

Looking Ahead

In the next few articles, I'll continue this theme on enumerable collections by covering topics such as adding sorting capabilities to your collections, versioning your enumerators, and fine-tuning your enumerators for better performance.

Download the Code

To download the accompanying source code for this article, click here.

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.

Page 2 of 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel