Using C#s Yield Keyword @WorldOfZeroDevelopment
Using C#s Yield Keyword  @WorldOfZeroDevelopment
Uploaded August 2019 | Updated November 2026, 1 hour ago
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](docs.unity3d.com/Manual/Coroutines.html).

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: docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield

Join the World of Zero Discord Server: discord.gg/hU5Kq2u
Using C#s Yield KeywordUsing Python and Argparse to Build Quick ScriptsRedesigning our C# Scripting in Unity ToolGenerating Images from SVGs with Unity and InkscapeExploring Zenject - Learning how to use Dependency Injection in UnityWhat Happens When You Snap Vertices To A Grid?Creating and Deleting Highscores - Online Highscores - Part 2Starting to Setup the Components - Day 1 - Building a Health DashboardAn Abstraction of our Character ControllerGetting Started Building Pong in my Terminal - Pong in Bash - Part 1Can You Hear Me Now - Trying and Failing to Use Unitys MicrophoneCreating and Using SSH RSA Tokens on Windows 10
World of Zero |

Using C#'s Yield Keyword

SHARE TO X SHARE TO REDDIT SHARE TO FACEBOOK WALLPAPER