What is the “yield” keyword used for in C#?

Technology CommunityCategory: C#What is the “yield” keyword used for in C#?
VietMX Staff asked 3 years ago
Problem

Consider:

IEnumerable<object> FilteredList()
{
    foreach( object item in FullList )
    {
        if( IsItemInPartialList( item )
            yield return item;
    }
}

Could you explain what does the yield keyword do there?

The function returns an object that implements the IEnumerable interface. If a calling function starts foreach-ing over this object the function is called again until it “yields”. This is syntactic sugar introduced in C# 2.0.

Yield has two great uses:

  • It helps to provide custom iteration without creating temp collections.
  • It helps to do stateful iteration.

The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won’t be created.

Another example:

public void Consumer()
{
    foreach(int i in Integers())
    {
        Console.WriteLine(i.ToString());
    }
}

public IEnumerable<int> Integers()
{
    yield return 1;
    yield return 2;
    yield return 4;
    yield return 8;
    yield return 16;
    yield return 16777216;
}

When you step through the example you’ll find the first call to Integers() returns 1. The second call returns 2 and the line “yield return 1” is not executed again.