using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Yield_Keyword_in_CSharp
{
class Program
{
static void printListValue(IEnumerable lst)
{
foreach (var item in lst)
{
Console.WriteLine("Value: " + item);
}
}
static IEnumerable getListValue()
{
List temp = new List();
for (int i = 0; i < 10; i++)
{
if (i > 5)
{
temp.Add(i);
}
Console.WriteLine("Counter:" + i );
}
return temp;
}
//static List getListValueYield()
//Error CS1624 The body of 'Program.getListValueYield()' cannot be an iterator block because 'List' is not an iterator interface type.
//return temp;
//Error CS1622 Cannot return a value from an iterator.Use the yield return statement to return a value, or yield break to end the iteration.
static IEnumerable getListValueYield()
{
List temp = new List();
for (int i = 0; i < 10; i++)
{
if (i > 5)
{
yield return i;
}
Console.WriteLine("Counter:" + i);
}
}
static void Main(string[] args)
{
printListValue(getListValue());
//Counter: 0
//Counter: 1
//Counter: 2
//Counter: 3
//Counter: 4
//Counter: 5
//Counter: 6
//Counter: 7
//Counter: 8
//Counter: 9
//Value: 6
//Value: 7
//Value: 8
//Value: 9
printListValue(getListValueYield());
//Counter: 0
//Counter: 1
//Counter: 2
//Counter: 3
//Counter: 4
//Counter: 5
//Value: 6
//Counter: 6
//Value: 7
//Counter: 7
//Value: 8
//Counter: 8
//Value: 9
//Counter: 9
Console.Read();
}
}
}