yield: the C# iterator

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store