I have the following code in which I am trying to take each element returned by an ICollectionView and translate it into a different object.
public IEnumerator GetEnumerator()
{
foreach (TOriginal original in _collectionView)
{
if (!Equals(original, null))
{
yield return GetTranslated(original);
}
else
{
yield return default(TTranslated);
}
}
}
If _collectionView is changed during the foreach (this is happening in my test app) then it throws an InvalidOperationException, but I can’t wrap the foreach loop in a try/catch because VisualStudio complains “‘yield return’ statement couldn’t appear in a try/catch block”.
How can I handle the exception?
Enumerators aren’t required to remain valid if the collection is modified. The standard behavior is that if the collection is modified in the middle of enumeration, the enumerator will throw an InvalidOperationException the next time
MoveNextis called.I believe letting the InvalidOperationException propagate is the proper behavior. Your enumerator will have the same semantics as all the standard collection classes, so consumers of your class will expect this.
If consumers of your class need to change the list during iteration, they should loop using an index value, and change the indexer as needed when they modify the list.