What is yield return in C#?
gpeipman
32.7K views
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;
}
}
}
}
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.