What is Yield? A Brief Overview

Yield is a feature of C# that is not present in its largest competitor, Java. Many of you have heard of it, but haven’t really used it, or may have dismissed it as “syntactic sugar.” Others might have never heard of it before. In short, it’s a way of replacing this:

public static List<int> ExampleList()
     List<int> ret = new List<int>();
     return ret;

With this:

public IEnumerable<int> ExampleYield()
    yield return 1;
    yield return 2;
    yield return 3;

So what happened here? First, we’ve opted away from <code>List<int></code> for a more interface-driven <code>IEnumerable<int></code> function return. Also, we’ve reduced the number of lines; by two to be exact. And somehow, we’ve managed to return a list of items without actually allocating a new list. That’s an important point to make, because we have completely avoided instantiating a new object. Read More…