Back
Close

What is yield return in C#?

gpeipman
8,847 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.

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;
}
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants