Mental Jetsam

By Peter Finch

C# Generics Enumerator Example

Posted by pcfinch on June 29, 2007

In order to implement a generics Enumerator, so that you can use a foreach on a class, in C# there is a bit of trick. If you are getting compilation error messages similar to the following then you have this problem.

'Results.GetEnumerator()' is either static, not public, or
has the wrong return type.

Using the generic type 'System.Collections.Generic.IEnumerator<T>'
requires '1' type arguments

In order to implement an Enumerator correctly you need a IEnumerable.GetEnumerator() member and your need to include System.Collections. although this seems to go against logic, I believe this is because the new generics Enumerator system uses the “old” Enumerator in some way.

using System.Collections.Generic;
using System.Collections;

public class Results : IEnumerable<SearchResult>
  private LinkedList<SearchResult> m_results;

  public IEnumerator<SearchResult> GetEnumerator() {
    foreach (SearchResult item in m_results)
      yield return item;

  IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();

This will allow you to do the following.

Results results ;
foreach (SearchResult result in results)

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: