Yield statement in C#

My great friend recently did on his wonderful blog covered in a recent post the basics of generators in Python. To further my own knowledge about generators, especially in the language I use most at work, I decided to port his permutation function to C#, yield statement and all.

To basically reiterate what my friend stated, the yield statement allows a function's state to be saved. For functions that are designed to generate a set of data to be iterated over this is great. Instead of computing the entire list and storing the results in memory, the function is able to pick up where it left off and generate the next element of the set when requested. Here is an example with a function that generates permutations.


   private static IEnumerable<string> Permutations(string input)
   {
      List<string> result = new List<string>();
      if (string.IsNullOrEmpty(input))
      {
         yield return string.Empty;
      }
      else
      {
         for (int i = 0; i < input.Count(); i++)
         {
            foreach (string permutation in Permutations(input.Substring(0, i) + input.Substring(i + 1)))
            {   
               yield return input[i] + permutation;
            }
         }
      }
   }
If you iterate over this function, you will notice that the entire list is never generated entirely in memory. The syntax would be something along the lines of:
   foreach (string permutation in Permutations("vegetable"))
      {
         System.Console.WriteLine(permutation);
      }
Thanks to my friend for helping me understand this topic and bring attention to features of a language I use every day.
Post a Comment