Home > SQL and .NET Blog, Uncategorized > Yield keyword in C# – Reduces LOC

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

http://Yuvahere.com

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: