Yield return break;

The easiest way to end a method call is making a return statement. However when we are using iterators in .net 2.0 we can make use of yield return I to return the next element in the collection. Yield return I does not end the method but returns the next value in the collection and halts the method until the next MoveNext is called. So how do you deal with a scenario where you want to end iteration early based on some reason. Well, you can make use of yield return break which simply breaks out of the method. If you have any finally block declared, those will also get executed. Let's have a look at an example.

image

 

image

In the above code, if i is greater than 10, I am simply breaking out of the iteration, otherwise I return the next value of i.  so from the result you will notice that we only print the first 10 numbers and than a finally block gets executed.

No Comments