ภาพรวม
คำสั่ง foreach ใน C# ใช้สำหรับ วนลูปผ่านทุกองค์ประกอบในอาร์เรย์หรือ Collection โดยไม่ต้องใช้ดัชนี (Index) โดยตรง รูปแบบง่ายกว่า for และลดโอกาสผิดพลาด Off-by-one Error
ตัวอย่างโปรแกรม
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] n = new int[10];
// เริ่มต้นค่าอาร์เรย์: 100, 101, 102, ..., 109
for (int i = 0; i < 10; i++)
n[i] = i + 100;
// วนลูปด้วย foreach - j คือค่าขององค์ประกอบ (ไม่ใช่ดัชนี)
foreach (int j in n)
{
int i = j - 100; // คำนวณดัชนีย้อนกลับ (สำหรับแสดงผล)
Console.WriteLine("Element[{0}] = {1}", i, j);
}
// แสดงชนิดของอาร์เรย์
Console.WriteLine(n); // System.Int32[]
Console.ReadKey();
}
}
}ผลลัพธ์
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 System.Int32[]
การเข้าถึงองค์ประกอบเฉพาะตัว (Random Access)
foreach ไม่ให้ดัชนีโดยตรง หากต้องการเข้าถึงองค์ประกอบเฉพาะตัว ใช้ดัชนีปกติ:
int secondElement = n[1]; // ได้ 101 (ดัชนี 1 = องค์ประกอบที่ 2)
Foreach vs For Loop
| คุณสมบัติ | foreach | for |
|---|---|---|
| เข้าถึงดัชนี | ไม่โดยตรง (ต้องนับเอง) | มีดัชนี i พร้อมใช้ |
| แก้ไขค่าในอาร์เรย์ | ไม่ได้ (Read-only iteration variable) | ได้ (arr[i] = newValue) |
| ประสิทธิภาพ | คล้ายกัน (Array: ใช้ Enumerator) | เร็วกว่าเล็กน้อย |
| รองรับ | Array, List, IEnumerable, ฯลฯ | Array, List (มี Count/Length) |
| ความปลอดภัย | สูงกว่า (ไม่มี IndexOutOfRange) | ต้องระวังขอบเขต |
Foreach กับการแก้ไขค่า (Modification)
// ผิด - ไม่สามารถกำหนดค่าให้ iteration variable ได้
foreach (int x in arr)
x = 10; // Compile Error: Cannot assign to 'x' because it is a 'foreach iteration variable'
// ถูก - ใช้ for loop แทน
for (int i = 0; i < arr.Length; i++)
arr[i] = 10;
// ถูก - ใช้ List และ ForEach method (แต่ไม่แนะนำสำหรับการ Mutate)
list.ForEach(x => x = 10); // ไม่ได้ผลกับ List เพราะ int เป็น Value Type
// ถูก - สำหรับ Reference Type
list.ForEach(obj => obj.Property = value); Forecast Pattern (C# 8.0+) - ได้ทั้ง Index และ Value
// ใช้ overload ของ Select ใน LINQ
foreach (var (index, value) in arr.Select((v, i) => (i, v)))
{
Console.WriteLine($"Index: {index}, Value: {value}");
}
// หรือใช้ Range/Indices (C# 8.0)
foreach (var i in ..arr.Length) // ไม่ได้มาตรฐาน ต้องเขียนเอง
// ปัจจุบันแนะนำ Select แบบบนข้อสังเกตสำคัญ
foreachใช้IEnumeratorภายใน - เรียกGetEnumerator(),MoveNext(),Current- สำหรับ Array: Compiler เพิ่มประสิทธิภาพเป็น Index-based loop แล้ว (No Enumerator Allocation)
- Iteration variable เป็น Read-only - ไม่สามารถ Assign ใหม่ได้
- หากต้องการดัชนี ใช้
forหรือ LINQSelect((v,i) => ...) foreachบนnullarray จะโยนNullReferenceException- ควรตรวจสอบ null ก่อน