Yield keyword in C# – Reduces LOC
Yield keyword is employed to reduce the allocation of arrays and by using a simple foreach iterative control structure.
Here’s a simple program which displays the first five even numbers.
1: private void LearnYield_Click(object sender, EventArgs e)
2: {
3: // this is the main program
4: string result = String.Empty;
5:
6: foreach (int value in ShowEvenNum(2, 5))
7: {
8: result = result + " - " + value.ToString();
9: }
10:
11: MessageBox.Show(result);
12: }
13:
14: // this method returns the list of first five even numbers
15: public static IEnumerable<int> ShowEvenNum(int number, int multiplier)
16: {
17: int loopValue = 0;
18: int numberResult = 0;
19:
20: while (loopValue < multiplier)
21: {
22: numberResult += number;
23: loopValue++;
24:
25: // this yield keyword will directly add to the return list
26: yield return numberResult;
27: }
28:
29: }
This code and its comments are self explanatory.
-Yuva
Categories: SQL and .NET Blog, Uncategorized
Comments (0)
Trackbacks (0)
Leave a comment
Trackback