You can see the difference in writing your method with yieldand without it in this example
static void Main(string[] args)
{
foreach (int i in List())
{
Console.WriteLine($"In List foreach {i}");
}
Console.WriteLine("*****");
foreach (int i in Yield())
{
Console.WriteLine($"In Yeild foreach {i}");
}
}
private static IEnumerable<int> List()
{
var inputList = new List <int> { 1, 2, 3 };
List<int> outputlist = new List<int>();
foreach (var i in inputList)
{
Console.WriteLine($"In List Method {i}");
outputlist.Add(i);
}
return outputlist.AsEnumerable();
}
private static IEnumerable<int> Yield()
{
var inputList = new List<int> { 1, 2, 3 };
foreach (var i in inputList)
{
Console.WriteLine($"In Yield Method {i}");
yield return i;
}
}
Here is the result:
In List Method 1
In List Method 2
In List Method 3
In List foreach 1
In List foreach 2
In List foreach 3
*****
In Yield Method 1
In Yield foreach 1
In Yield Method 2
In Yield foreach 3
In Yield Method 3
In Yield foreach 3
source
share