Reputation: 2514
My class implements IEnumerable. And these two ways to code GetEnumerator method can be compiled:
public IEnumerator GetEnumerator()
{
yield return Database[id].GetEnumerator();
}
and
public IEnumerator GetEnumerator()
{
return Database[DatabaseId].GetEnumerator();
}
where Database[id] is List. Is any difference between these implementations?
Upvotes: 2
Views: 739
Reputation: 1062550
The reason that compiles is because you are being unclear what the enumerable is. If you make it generic it becomes more obvious:
public IEnumerator<Foo> GetEnumerator()
{
return Database[id].GetEnumerator();
}
vs
public IEnumerator<IEnumerator<Foo>> GetEnumerator()
{
yield return Database[id].GetEnumerator();
}
Your yield return
version is not yielding the result: it is yielding the iterator - it is an iterator-of-iterators, an enumerator-of-enumerators. And not in a good way. Basically, "don't do that".
Upvotes: 6