locked
Yield Statement in C# RRS feed

  • Question

  • User-1366948256 posted

    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.

     public static IEnumerable<int> Square(int min, int max)
    {
    for (int i = min; i < max; i++)
    {
    yield return i*i;
    }
    }

    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.

     foreach (int i in Square(1, 10))
    {
        Response.Write(i.ToString() + " ");
     }
    
    
    And output will be like 1,4,9,16,25,36,49,64,81

     




    Saturday, May 1, 2010 3:55 PM

All replies

  • User-725366812 posted

    Hi, Jalpesh,

    This is very interesting, I agree yield is very powerful command.  But your post is a little difficult to read, so here is it again cleaned up.  Also changed the < to <=, I think it is more sense that the Square(1, 10) should go from 1...100 rather than 1...81:

    public static IEnumerable<int> Square(int min, int max)
    {
        for (int i = min; i <= max; i++)
        {
            yield return i*i;
        }
    }

    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.

    foreach (int i in Square(1, 10))
    {
        Response.Write(i.ToString() + " ");
    }

    And output will be like 1,4,9,16,25,36,49,64,81,100.

    Regards,

    ~ mellamokb

    Saturday, May 1, 2010 11:08 PM
  • User-1366948256 posted

    Thanks dear

    Monday, May 3, 2010 3:37 PM