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




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. It avoids using a temporary list to store intermediate values.
  2. It simultaneously returns one value at a time instead of the entire collection.

Important Point Regarding The Yield Keyword


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



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

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250