I’ve written a class that implements IEnumerable<T>. I have a method that returns MyClass. If I try to yield return from within that method, the compiler tells me “… cannot be an iterator block because … is not an iterator interface type”.
So, how can I define my own interface iterator type? Does it have to be “abstract” (can’t have any methods defined)?
What I want to do is write a bunch of chainable methods, so every method should return an instance of MyClass. But I need MyClass to be some kind of enumerable. Rather than using some underlying data type, I was hoping I could just yield return everywhere.
@Oded:
class SharpQuery : IEnumerable<HtmlNode>
{
public SharpQuery Find(string selector)
{
foreach (var n in this)
{
// filter the results
yield return node;
}
}
}
No, that’s not possible. To see why consider that you have a class
Zoothat implementsIEnumerable<Animal>but also has lots of other members. AZoois anIEnumerable<Animal>but not necessarily vice versa – a sequence of animals is just a sequence of animals. There’s no zoo keeper, no shops, no entrance fee or any of the other things that makes a zoo a zoo.When you use
yield return xthe return type cannot beZoobecause you don’t have a zoo – you just have a sequence of animals.What you can do instead is to call it as
new Zoo(foo())wherefooreturns anIEnumerable<Animal>and add a constructor toZoothat accepts anIEnumerable<Animal>.