Really, how do you make enumerations?

G

Gustaf

I had VS (2008) telling me my class isn't enumerable when trying to use a foreach loop. This happens quite often, and every time I Google around for an hour trying to find a solution that applies to my case. It needs to be understandable and easy to implement. It needs to work with List<T> collections. It should be the best practice in .NET 3.5. Can anyone point me once and for all to the right solution? The best I can find right now is this:

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

But I don't want to write all that every time I make a collection lass, and I don't like the public class variable in the enumerator class. Didn't enumerations get a lot easier in .NET 2.0?

Gustaf
 
J

Jon Skeet [C# MVP]

But I don't want to write all that every time I make a collection lass,
and I don't like the public class variable in the enumerator class.
Didn't enumerations get a lot easier in .NET 2.0?

Implementing IEnumerable and IEnumerator (and the generic equivalents)
became a lot easier in C# 2 with iterator blocks (method
implementations using "yield return" and "yield break" statements).

See the following links for a couple of articles and a free chapter
from my book (C# in Depth) which covers iterator blocks:
http://csharpindepth.com/Articles/Chapter11/StreamingAndIterators.aspx
http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx
http://www.manning-source.com/books/skeet/Chapter6sample.pdf

Jon
 
M

Marc Gravell

t needs to work with List<T> collections.
Can you clarify what you have already? If you have a class that is
encapsulating a single list, then you can simply forward the list's
enumerator:

class Test : IEnumerable<string>
{
private List<string> innerList = new List<string>();

public IEnumerator<string> GetEnumerator()
{
return innerList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

If you have multiple lists, you can use an iterator block to flatten
them:

class Test : IEnumerable<string>
{
private List<string> listA = new List<string>(),
listB = new List<string>();

public IEnumerator<string> GetEnumerator()
{
foreach (string s in listA) {yield return s;}
foreach (string s in listB) { yield return s; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

If that doesn't help, can you clarify what you have?

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top