Ads Top

Using Yield Keyword in C#

yield keyword is used for customized iteration in a collection. It is used inside an iterator block which return iterator type. It can not be used directly inside Main method which is void type. Uses of yield keyword : No need to create temporary list. As it returns value back to caller for every match found. It keeps track of last iterated value. So it does not need to iterate the same value again. To return any enumerator value by writing this code “yield return ”. To return break like “yield break”. We have to keep in mind that yield statement only appears associated with iterative block, which can be implemented as the body of a method or function. Now lets have an example. We have a list with 20 numbers. But i want to display only even numbers. we can also get even number without using yield keyword. But in this case an extra temp collection need to be created. but with the help of yield keyword we can directly get the even numbers.




1:  static List<int> numbers = new List<int>();  
2:  // add all number in numbers list form 1 to 20  
3:  static void NumberList()  
4:  {  
5:  for (int i = 1; i<= 20; i++)  
6:  {  
7:  numbers.Add(i);  
8:  }  
9:  }  
10:  // This method return IEnumerable of even number between 1 to 20  
11:  static IEnumerable<int> EvenNumber()  
12:  {  
13:  foreach (int i in numbers)  
14:  {  
15:  if (i % 2 == 0) yield return i;  
16:  }  
17:  }  
18:  static void Main(string[] args)  
19:  {  
20:  NumberList();  
21:  IEnumerable<int> EvenNumberList = EvenNumber();  
22:  // Now display the even number  
23:  foreach (int i in EvenNumberList)  
24:  {  
25:  Console.WriteLine(i);  
26:  }  
27:  Console.ReadKey();  
28:  }

There are few restrictions to use “yield” keyword.
  • Unsafe block are not allowed.
  • A “yield” return statement cannot be located anywhere inside a try-catch block. We can place “yield” within try if try-catch block contains finally block.
  • We cannot put “yield” keyword within finally block.
Powered by Blogger.