December 2007
Intermediate to advanced
896 pages
19h 57m
English
You have a requirement that if an iterator encounters malformed or out-of-bounds data that the iterations are to stop immediately.
It is possible to throw an exception from an iterator, which terminates the iterator and the foreach loop, but a controlled stop to an iterator should not be an exceptional condition. To do this, you can use the yield break statement within your iterator:
public class UpperLimitList<T> : IEnumerable<T>
{
private List<T> _items = new List<T>();
private bool noMoreItemsCanBeAdded;
private int upperLimit = -1;
public int UpperLimit
{
get {return (upperLimit);}
set {upperLimit = value;}
}
public void Add(T name)
{
_items.Add(name);
}
public IEnumerator<T> GetEnumerator()
{
for (int index = 0; index < _items.Count; index++)
{
if (noMoreItemsCanBeAdded)
{
yield break;
}
else
{
if (upperLimit >= 0 && index >= upperLimit-1)
{
noMoreItemsCanBeAdded = true;
}
yield return (_items[index]);
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}The way to terminate an iterator, and thus terminate the foreach loop, is to use the yield break statement. This statement has the same effect as simply exiting from the function. This yield break statement can be used only within an iterator block.
To use the UpperLimitList, see the following code:
public static void TestYieldBreak() { //Create UpperLimitList and fill it with data UpperLimitList<string> gatePasses = new UpperLimitList<string>() ...Read now
Unlock full access