I have an array of object with the starting length of 4, and each time the Add method reaches the length, the length doubles. The array implements IEnumerable:
public ObjectArrayCollection()
{
this.objectArray = new object[ObjectArrayCapacity];
Count = 0;
}
public int Count { get; protected set; }
public object this[int index]
{
get => this.objectArray[index];
set => this.objectArray[index] = value;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public ObjectArrayEnumeration GetEnumerator()
{
return new ObjectArrayEnumeration(objectArray);
}
and a class that implements IEnumeration:
public ObjectArrayEnumeration(object[] objectArray)
{
this.objectArray = objectArray;
}
public object Current
{
get
{
try
{
return objectArray;
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
public bool MoveNext()
{
position++;
return position < objectArray.Length;
}
public void Reset()
{
position = -1;
}
The "possition < objectArray.length" condition is not good since objectArray can contain null if objects added don't fill the array. I sent the Count to the enumerator:
public ObjectArrayEnumeration GetEnumerator()
{
return new ObjectArrayEnumeration(objectArray, Count);
}
but since I need them both I was told that the enumerator should encapsulate objectArray. I've tried this:
public IEnumerator GetEnumerator()
{
return objectArray.GetEnumerator();
}
but this way I don't enumerate the values. I am new with C# and learning and I've run out of ideas. How can the enumerator encapsulate the objectArray?