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.

## No comments:

Post a Comment