Skip to content

EN CSharp Iterators

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Iterators, yield and async sequences

Manual C# · Examples UO

The method with yield return gives the elements as they are enumerated, yield break completes the sequence. Its body usually begins to work not when creating a sequence, but when enumerating. IAsyncEnumerable<T> supports asynchronous receipt of elements via await foreach.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
System.Collections.Generic.IEnumerable<int> Numbers()
{
    yield return 1;
    yield return 2;
}
foreach (int value in Numbers()) System.Console.WriteLine(value);

Result:

1
2
IEnumerable<int> Range(int count)
{
    for (int i = 0; i < count; i++) yield return i;
}
foreach (int value in Range(3))
{
    UO.Print(value.ToString());
}
async IAsyncEnumerable<int> Ticks()
{
    for (int i = 0; i < 3; i++)
    {
        await WaitAsync(10);
        yield return i;
    }
}
await foreach (int tick in Ticks())
{
    UO.Print($"Tick={tick}");
}

Do not let a deferred sequence access the game API after its script has ended. Source data can change before enumeration. ToArray materializes the current elements; reference-valued elements still refer to the same objects.

Official documentation: Iterators, yield, and async sequences - Microsoft Learn.

Clone this wiki locally