Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between yield and return statement in C#.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.54k
    Comment on it

    return statement in C#

    Example to demonstrate return statement:

    static int SimpleReturn()
    {
        return 1;
        return 2;
        return 3;
    }
    
    static void Main(string[] args)
    {
        Console.WriteLine(SimpleReturn());
        Console.WriteLine(SimpleReturn());
        Console.WriteLine(SimpleReturn());
        Console.WriteLine(SimpleReturn());
    }

     

    Output:

    1

    1

    1

    1

    In above example int SimpleReturn function three returns are mentioned but no matter how many times this function is called from anywhere, here from main the function will always return first value i.e 1.

    Yield statement in C#

    Example to demonstrate yield statement:

    static IEnumerable<int> YieldReturn()
    {
        yield return 1;
        yield return 2;
        yield return 3;
    }
    static void Main(string[] args)
    {
        foreach (int i in YieldReturn())
        {
            Console.WriteLine(i);
        }
    }

    Output:

    1

    2

    3

    The only difference between yield and return is whenever yield statement is encountered in a function, the execution of function is suspended and a value is send back to the caller but because of yield whenever the function is called again, the execution of function begin where it left off previously. When resumed, the function continues execution immediately after the last yield run. Thus yield allows a function to produce a series of values over time. The only requirement for yield return statement is that the function containing yield should return an IEnumerable and no matter from where that function is called it should be called from an iteration block i.e foreach statement.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: