0

Looking at the source code for many collections it seems that they always have a dedicated Enumerator class with a lot of code written to assure the enumeration goes smoothly without problems.

My question is, if instead of coding a specific class for my collection I instead implemented an Enumerator for a collection as such:

    public IEnumerator<T> GetEnumerator ()
    {
        int startingVersion = _version;

        for (int i = 0; i < _count; i++)
        {
            if (startingVersion != _version)
                throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");

            yield return _items[i];
        }
    }

Would there be problems with this approach?

Dan
  • 3,647
  • 5
  • 20
  • 26
KainDefiant
  • 233
  • 2
  • 6
  • 1
    Related: [When should I separately implement IEnumerator?](https://stackoverflow.com/questions/24142614/when-should-i-separately-implement-ienumeratort) – Theodor Zoulias May 28 '22 at 14:37
  • 1
    These two questions are also worth reading: [Enumerator Implementation: Use struct or class?](https://stackoverflow.com/questions/384511/enumerator-implementation-use-struct-or-class) / [Writing custom IEnumerator with iterators](https://stackoverflow.com/questions/432600/writing-custom-ienumeratort-with-iterators) – Theodor Zoulias May 28 '22 at 14:44

0 Answers0