What Does yield Do In C#: A Simplified View For Beginners
What does yield do in C#? Explore the benefits of using C# yield keyword with large datasets and best practices for implementation. One more tool to leverage!
What does yield do in C#? Explore the benefits of using C# yield keyword with large datasets and best practices for implementation. One more tool to leverage!
If you're newer to C# or programming in general, you may have used an iterator and not even realized it. Iterators can be a performant and effective tool that we have access to as .NET developers that allow us to traverse collections of data. Because one of the requirements of an iterator is that it must implement the IEnumerable interface, the results of an iterator can only be enumerated over. For example, you could use the results of an iterator in a foreach loop but you could not directly index into the iterator results (like you could an array) without some additional steps. Another requirement of iterators is that they use a special keyword called "yield" so that they can yield and return the individual elements that are to be provided to the caller of the iterator. In a nutshell,…
Yield: A Little Background The yield keyword in C# is pretty cool. Being used within an iterator, yield lets a function return an item as well as control of execution to the caller and upon next iteration resume where it left off. Neat, right? MSDN documentation lists these limitations surrounding the use of the yield keyword: Unsafe blocks are not allowed. Parameters to the method, operator, or accessor cannot be ref or out. A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block. A yield break statement may be located in a try block or a catch block but not a finally block. So what does this have to do with API specifications? A whole lot really, especially if you're dealing…