KainDefiant
KainDefiant

Reputation: 283

Implementing an Enumerator for a collection using a simple iterator block

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?

Upvotes: 0

Views: 151

Answers (0)

Related Questions