C# yield

I've seen the "yield" keyword here and there... but I've never really cared to learn what it does. Until now. Actually, it's my understanding that it's more or less a convenience keyword like "var."

In short, "yield" allows you to return an IEnumerable without creating a List.

Example: (old way)

IEnumerable<Car> FindBlueCars(){
    var blueCars = new List<Car>();
    foreach (var c in _allCars)
        if (c.IsBlue())
            blueCars.Add(c);
    return blueCars;
}

Example: (new way)

IEnumerable<Car> FindBlueCars(){
    foreach (var c in _allCars)
        if (c.IsBlue())
            yield return c;
}

Saves some typing. MSDN reference for yield..aspx)

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Read me blog on entrepreneurship: Techneur Follow me on Twitter: @jprichardson

-JP

If you made it this far, you should follow me on Twitter.

-JP

Want to test-drive Bitcoin without any risk? Check out my bitcoin wallet Coinbolt. It includes test coins for free.

comments powered by Disqus