Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

foreach: practical reference

foreach: practical reference: foreach enumerates a source through the enumerator pattern; the generated finally disposes the enumerator only when it satisfies the Dispose or IDisposable pattern.

Version: C# language; verified against C# 14 reference

Syntax

foreach /* grammar-specific form */

foreach enumerates a source through the enumerator pattern; the generated finally disposes the enumerator only when it satisfies the Dispose or IDisposable pattern.

Use it for sequential reading without manually calling MoveNext.

Modifying the collection usually invalidates the enumerator; the iteration variable is not an index.

An empty source skips the body; await foreach requires the asynchronous pattern.

The complete program actually uses foreach; its exact expected stdout is 6.

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;

var sum = 0; foreach (var value in new[] { 1, 2, 3 }) sum += value; Console.WriteLine(sum);

Result

6

The complete program actually uses `foreach`; its exact expected stdout is `6`.

Sources