Managed Extensions: Adding Enumeration to Your Classes
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);
// m_articles is a class-level object of type ArticleCollection
IEnumerator* en = m_articles->GetEnumerator();
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 languagesmdash;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.
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.