yield: the C# iterator

himanshu motwani
1 min readApr 28, 2022

yield is a very powerful contextual keyword in C# language. While you use this keyword you are basically indicating to the compiler that the code block is an iterator block. Using yield helps a developer save memory and also prevents instantiations of temporary IEnumerable<T> objects. Let’s understand this with a very simple example:-

public List<int> GetValuesGreaterThan100(List<int> sourceList)
{
List<int> tempList = new List<int>();

foreach(var value in sourceList)
{
if (value > 100)
{
tempList.Add(value);
}
}
return tempList;
}

In the above example, we are returning a list that satisfies a certain condition. If you notice closely, we are using a temporary list i.e. tempList to just hold the result and then return. This temporary list eats a block of memory, which is very precious from a developer’s point of view to run the application smoothly. The below snippet shows how we can avoid this :-

public IEnumerable<int> GetValuesGreaterThan100(List<int> sourceList)
{
foreach (var value in sourceList)
{
if (value > 100)
{
yield return value;
}
}
}

In order to prevent the temporary collection from being used, developers can use yield. Yield gives out results according to the result set enumeration.

Note:- When using yield, it returns IEnumerable<T> type.

Thanks,

Himanshu M.

--

--