I created a custom collection that implements IEnumerable(T) and a custom IEnumerator(T).
I also added an Add() method to the custom collection which looks like this:
public void Add(T item)
{
T[] tempArray = new T[_array.Length + 1];
for (int i = 0; i < _array.Length; i++)
{
tempArray[i] = _array[i];
}
tempArray[_array.Length] = item;
_array = tempArray;
tempArray = null;
}
The implementation is based on this example http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx.
When I do a foreach loop with my array I would like to prevent collection modification (like calling Add() inside the loop) and throw a new InvalidOperationException. How would I be able to do that?
You'd need to have a version ID within your class. Increment it on entry to Add. When you create an iterator (in the GetEnumerator() call) you would remember the version number - and on each iteration, you'd check whether the version number is still what it was to start with, throwing otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With