Articles → CSHARP → Yield Keyword In C#

Yield Keyword In C#






Purpose






using System;
using System.Collections.Generic;

namespace Yield_Sample {
  class Program {
    static void Main(string[] args) {
      Program prog = new Program();
      foreach(int i in prog.ReturnList())
      Console.WriteLine(i);

      Console.ReadLine();
    }

    public IEnumerable < int > ReturnList() {
      int count = 10;
      int[] coll = new int[count];

      for (int i = 1; i <= count; i++) {
        coll[i - 1] = i;
      }

      return coll;
    }
  }
}




Picture showing loop through the collection without using the yield function
Click to Enlarge



using System;
using System.Collections.Generic;

namespace Yield_Sample {
  class Program {
    static void Main(string[] args) {
      Program prog = new Program();
      foreach(int i in prog.ReturnList())
      Console.WriteLine(i);

      Console.ReadLine();
    }

    public IEnumerable < int > ReturnList() {
      int count = 10;

      for (int i = 1; i <= count; i++) {
        yield
        return i;
      }
    }
  }
}




  1. We are not using any temporary list variable to store the values.
  2. One value is returned at a time instead of the whole collection.

Important Point Regarding Yield Keyword


  1. You cannot return yield statement in try-catch block.
  2. You cannot return out or ref parameters using yield keyword.
  3. You cannot use yield statement inside anonymous method.
  4. You cannot use yield statement inside unsafe method.



Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, August 28, 2018

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250