One of the most interesting statements in C# language is probably the yield statement. The yield statement can be used to return multiple objects from a method while still retaining its state. I know what you are probably thinking..."What the hell does that mean?" Well if you look at the example code below I made a method which returns each value in the Fibonacci Sequence so you can print the output to the console.
1: static void Main(string[] args) {
2: foreach (int val in FibonacciSequence(10)) {
3: Console.WriteLine(val.ToString());
4: }
5: Console.ReadLine();
6: }
7:
8: static IEnumerable<int> FibonacciSequence( int iterations ) {
9: yield return 1;
10: int[] cachedVals = new int[]{0,1};
11:
12: for (int i = 1; i < iterations; i++) {
13: yield return cachedVals.Sum();
14: cachedVals = new int[] { cachedVals[1], cachedVals.Sum() };
15: }
16: }
The yield statement is also available in many other programming languages such as Ruby and C++. Unfortunately, many people seem either not to know about it or find another way to write the code. For example, the Fibonacci code above could have been accomplished by using recursion. In any case, the yield statement is just another tool in your programming arsenal.
Happy Coding!