CKTIS / C#
iterators and generators: practical reference
iterators and generators: practical reference: An iterator produces elements step by step through yield and retains state between MoveNext calls.
Version: C# language and .NET 10 reference runtime
Syntax
// iteratorsAn iterator produces elements step by step through yield and retains state between MoveNext calls.
Use it for lazy sequences without building a complete collection.
Code runs during enumeration rather than when the method is called.
Dispose executes the iterator finally; an infinite source needs a limit or cancellation.
The complete program actually uses iterators and generators; its exact expected stdout is 0,1,2.
Examples
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;
Console.WriteLine(string.Join(",", Count(3))); static IEnumerable<int> Count(int length) { for (var i = 0; i < length; i++) yield return i; }
Result
0,1,2
The complete program actually uses `iterators and generators`; its exact expected stdout is `0,1,2`.