Advertisement

Using C#'s Yield Keyword

Using C#'s Yield Keyword C#'s Yield operator allows you to define enumerable sets which can be dynamically generated and are lazily evaluated. This enables a number of fun things that would be difficult otherwise such as infinite lists. Some other frameworks have also taken advantage of `yield` to power different features like [Unity 3D's Coroutines](

When used in a function or property which returns an `IEnumerable`, yield will provide two features. You may `return` the next value in the set or `break` out of the loop - effectively terminating the set. Values `return`ed from a `yield` keyword are composed into the enumerable set as your code evaluates. Yield statements are evaluated lazily (meaning the function generating the enumerable object is not generated completely before the first element is returned), this means that after returning with `yield` the code in the function will continue from the point it returned from including preserving the state (such as local variable values).

Using these concepts we can create a function which returns all positive integers between 1 and a max value.

```csharp
// Note: you'll need to replace the IEnumerable{int} with correct syntax as well as the ≥ symbol.
public static IEnumerable{int} PositiveInts(int max) {
int i = 1;
while(true) {
yield return i++;
if (i ≥ max) {
yield break;
}
}
}
```

* `yield return`: returns the next value in an `IEnumerable`.
* `yield break`: marks the end of the `IEnumerable`.

More information about using `yield` with some other examples is available here:

Join the World of Zero Discord Server:

world of zero,lets make,yield,contextual keyword,keyword,yield contextual keyword,c#,dotnet,.net,csharp,yield return,yield break,.net yield,c# yield,using c# yield,yield example,c# yield example,IEnumerable,Iterator,c# reference,example,tutorial,how to,C# yield Keyword,c# yield return ienumerable,yield in c#,c# yield ienumerable,programming,development,software development,dotnet core,

Post a Comment

0 Comments