-1

I'm trying to understand how to implement generic collections and the IEnumerator interface; I'm using the Documentation provided to do so.

In the given example the enumerator's method MoveNext() is implemented as follows:

public bool MoveNext()
{
    //Avoids going beyond the end of the collection.
    if (++curIndex >= _collection.Count)
    {
        return false;
    }
    else
    {
        // Set current box to next item in collection.
        curBox = _collection[curIndex];
    }
    return true;
}

curIndex is used to as index for BoxCollection, which implements ICollection. If I try to do the same I get "Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.ICollection...".

Is the documentation wrong, or is it me not doing something correctly?

2 Answers2

3

BoxCollection itself implements the indexer:

public Box this[int index]
{
    get { return (Box)innerCol[index]; }
    set { innerCol[index] = value; }
}

(line 129-133 of the sample you linked to)

You're right that you can't use the indexer on a class that implements ICollection<T> - unless that class also implements an indexer.

Tim
  • 14,999
  • 1
  • 45
  • 68
1

In the sample code in the documentation _collection is a BoxCollection, which is an ICollection also, but in that manifestation it’s typed as a BoxCollection and can therefore have indexing applied because BoxCollection implements a this[int] indexer property

Had the sample code declared _collection as some ICollection<T>, their code would get the same error yours does; in other words the indexability comes from their variable being an indexable type, which is unrelated to it also implementing ICollection (ICollection does not mandate provision of an indexer)

Caius Jard
  • 72,509
  • 5
  • 49
  • 80