Home > DeveloperSection > Forums > yield Statement in C#
Ankit Singh

Total Post:341

Points:2389
Posted on    November-27-2015 9:43 PM

 C# C#  .NET 
Ratings:


 1 Reply(s)
 209  View(s)
Rate this:
 i want to use yield in c# how to use please help me.


aditya kumar Patel

Total Post:242

Points:1722
Posted on    November-27-2015 9:49 PM

With yield keyword, the control moves from the caller to source and from the source back to the caller .
yield statement can be used in two forms: yield return <expression>;

yield return statement returns each element at at time.
Yield return allows you to run custom iteration without temp collection.

using System;
using System.Collections.Generic;
namespace RandomNumberApp
{
    class RandomNumber
    {
        static void Main(string[] args)
        {
            foreach (int i in PrintRandomNumbers(10))
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();

        }
        static IEnumerable<int> PrintRandomNumbers(int counter)
        {
            Random rand = new Random();
            for (int i = 0; i < counter; i++)
            {
                yield
                return rand.Next();
            }
        }
    }
}

 


Don't want to miss updates? Please click the below button!

Follow MindStick