Hidden Secrets of C# Tip 1: Yield Return, Yield Break

If you ever wanted to return the generic collection of items from an method, what do you do? you may do like this..

public List<int> LoadEvenNumbers(){
         List<int> items = new List<int>();
         for(int i = 0; i<100;i++)
         {
                  if(i % 2 == 0) items.Add(i);                 
         }  
}

But, there is better way to achieve the same using Iterators..

public IEnumerable<int> LoadEvenNumbers(){
         for(int i = 0; i<100;i++)
         {
                  if(i % 2 == 0) yield return i;                 
         }  
}

Surprise.. isn’t it…

For more details about Yield Return and Yield Break.. refer MSDN documentation here..

http://msdn.microsoft.com/en-us/library/9k7k7cf0(v=vs.80).aspx

  • Aungkyaw92

    It was really cool! Thanks!!