The di erence between break and yield break C# with Example



The di erence between break and yield break C# with Example

Using yield break as opposed to break might not be as obvious as one may think. There are lot of bad examples 
on the Internet where the usage of the two is interchangeable and doesn't really demonstrate the difference. 
The confusing part is that both of the keywords (or key phrases) make sense only within loops (foreach, while...) So 
when to choose one over the other? 
It's important to realize that once you use the yield keyword in a method you effectively turn the method into an 
iterator. The only purpose of the such method is then to iterate over a finite or infinite collection and yield (output) 
its elements. Once the purpose is fulfilled, there's no reason to continue method's execution. Sometimes, it 
happens naturally with the last closing bracket of the method }. But sometimes, you want to end the method 
prematurely. In a normal (non-iterating) method you would use the return keyword. But you can't use return in an 
iterator, you have to use yield break. In other words, yield break for an iterator is the same as return for a 
standard method. Whereas, the break statement just terminates the closest loop. 
Let's see some examples: 
///  
/// Yields numbers from 0 to 9 
///  
/// {0,1,2,3,4,5,6,7,8,9} 
public static IEnumerable YieldBreak() 
{ 
for (int i = 0; ; i++) 
{ 
if (i < 10) 
{ 
// Yields a number 
yield return i; 
} 
else 
{ 
// Indicates that the iteration has ended, everything 
// from this line on will be ignored 
yield break; 
} 
} 
yield return 10; // This will never get executed 
} 
///  
/// Yields numbers from 0 to 10 
///  
/// {0,1,2,3,4,5,6,7,8,9,10} 
 

public static IEnumerable Break() 
{ 
for (int i = 0; ; i++) 
{ 
if (i < 10) 
{ 
// Yields a number 
yield return i; 
} 
else 
{ 
// Terminates just the loop 
break; 
} 
} 
// Execution continues 
yield return 10; 
} 

0 Comment's

Comment Form