Yield Return Statement in C# | HOW TO - Code Samples

preview_player
Показать описание
#coding #codingbootcamp #softwaredeveloper

I want to talk about the yield keyword in C#. I think it’s a powerful C# feature and I wanted to highlight the benefits.

The yield keyword tells the compiler that the method in which it appears is an iterator block. An iterator block, or method, returns an IEnumerable as the result. And the yield keyword is used to return the values for the IEnumerable.

An interesting thing about IEnumerable is that it is lazily evaluated. Calling a method with an iterator block doesn’t run any code. It’s only when the IEnumerable is iterated over, or enumerated, that we get the actual values. I’ll talk about this more later.

The yield keyword on it’s own doesn’t do anything, you have to combine it with the return or break statement:

yield return — provides the next value of the iterator
yield-break — signals the end of iteration

You can use the yield break statement to stop iteration and exit the iterator block.

In C# 8 we got the IAsyncEnumerable type which allows us to iterate over a collection asynchronously with the yield statement.

Lots of Great How Tos and Code Samples! Make sure to like and subscribe!
Рекомендации по теме
visit shbcf.ru