How many programmers you know use ‘yield‘? Seriously, if you have an occasion, ask them – I’m afraid you will notice a strange thing – everybody heard about it but (almost) nobody (including me) uses it. Time to change it! Why? Because ‘yield‘ was introduced in C# 2.0 (yeeeah, it’s that old!) and can help you get rid of some of the ‘temp’ collections in your code and, what’s more important, it may prevent you from System.OutOfMemory exception.

Let’s get rid of temporary collection!

That’s it, it occurs you don’t need at least half of the temporary collections you use! Don’t believe me? Have a look at the example below (full code here).

Let’s assume we have a list of animals species and we want to display only the 3-letters-long ones.

We can do it in a classical approach:

List<string> temp = new List<string>(); foreach (var data in Animals) { if (data.Length == 3) { temp.Add(data); } } return temp;

But we have to declare a ‘temp‘ list in a right scope… That’s so boring!

What about the below approach:

foreach (var data in Animals) { if (data.Length == 3) { yield return data; //(1) } } yield return "AnimalFromOutsideTheList"; //(2)

What does it mean?

(1) yield return data; will in fact pause the iteration and pass a data value to the caller. The caller will operate on the value and when it needs the next value from GetAnimalsWith3LetterNameWithYield() method, the code will be resumed in the line marked with (1) in a comment. So it means line (1) is executed only at the exact moment when it’s needed. Excellent!

(2) yield return “AnimalFromOutsideTheList”; – it just adds additional string to the returning list, just in case you suspected it can be used only in a loop. As you can see – ‘yield‘ can be used in any place but putting it inside a loop has a greater sense ;).

What’s next?

In the next posts I will show you how placing yield keyword in your code affects RAM usage. I will also focus on other ‘yield break‘. So stay tuned!

PS

Happy Easter everyone!

Featured image by Patricia Jekki