What is yield return in C#?
gpeipman
36.6K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Yield return in C#
Yield return in C# language feature that allows us to write shorter methods that operate on collections. Demo below shows how with yield return we don't have to define collection or list that holds elements returned by method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
class Program
{
private static IEnumerable<string> _plants = new[] { "Apple", "Pear", "Sunflower", "Carrot" };
static void Main(string[] args)
{
Console.WriteLine("Classic:");
foreach(var fruit in GetFruits())
{
Console.WriteLine(fruit);
}
Console.WriteLine("\r\nYield return:");
foreach (var fruit in GetFruitsWithYield())
{
Console.WriteLine(fruit);
}
}
private static IEnumerable<string> GetFruits()
{
var result = new List<string>();
foreach(var plant in _plants)
{
if(plant == "Apple" || plant == "Pear")
{
result.Add(plant);
}
}
return result;
}
private static IEnumerable<string> GetFruitsWithYield()
{
foreach (var plant in _plants)
{
if (plant == "Apple" || plant == "Pear")
{
yield return plant;
}
}
}
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content