April 24, 2019
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