Yield statement in C#

Yield statement is one of most interesting statement in the C# 2.0. I have heard about lot of yield statement but today i have learned about yield statement. Yield statement can be used to return multiple object from a method while retaining its state. You can get item in sequence with help of yield.Let take a simple example to see the power or yield statement.

Let’s create one example which will help you the understand how its works Let create a function will return the square each time this function is called.

Code Snippet

  1. public static IEnumerable Square(int min, int max)
  2. {
  3. for (int i = min; i < max; i++)
  4. {
  5. yield return i*i;
  6. }
  7. }

Now each time this method is called it will return the square of current value within a given range and its also maintains the state between calls. Let create for each loop to call the the square function above.

Code Snippet

  1. foreach (int i in Square(1, 10))
  2. {
  3. Response.Write(i.ToString() + ” “);
  4. }

And here will be the output in the browser.

So it will create IEnumerable without implementing any interface and lesser code.

Happy Programming..

Technorati Tags: C# 3.0,C# 4.0,Yield