ภาพรวม
คำสั่ง continue ใน C# ใช้เพื่อ ข้ามส่วนที่เหลือของรอบลูปปัจจุบัน และ กระโดดไปตรวจสอบเงื่อนไขลูปทันที (Retest Condition) ต่างจาก break ที่ออกจากลูปเลย
ตัวอย่าง: Continue ใน While Loop
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
int a = 10;
while (a < 20)
{
// ข้ามการพิมพ์เมื่อ a == 15
if (a == 15)
{
a = a + 1; // สำคัญ: เพิ่ม a ก่อน continue ไม่งั้น Infinite Loop!
continue; // ข้าม Console.WriteLine ไปตรวจสอบ while (a < 20) ทันที
}
Console.WriteLine("ค่าของ a: {0}", a);
a++;
}
Console.ReadLine();
}
}
}ผลลัพธ์
ค่าของ a: 10 ค่าของ a: 11 ค่าของ a: 12 ค่าของ a: 13 ค่าของ a: 14 ค่าของ a: 16 ค่าของ a: 17 ค่าของ a: 18 ค่าของ a: 19
สังเกต: ไม่มี 15 เพราะถูก continue ข้าม
คำอธิบายลำดับการทำงาน (เมื่อ a = 15)
| ขั้นตอน | คำสั่ง | ค่า a | หมายเหตุ |
|---|---|---|---|
| 1 | ตรวจสอบ while (a < 20) | 15 | True - เข้าลูป |
| 2 | if (a == 15) | 15 | True - เข้าเงื่อนไข |
| 3 | a = a + 1 | 16 | เพิ่มก่อน Continue (สำคัญ!) |
| 4 | continue | 16 | ข้าม Console.WriteLine, ไปตรวจสอบ while ทันที |
| 5 | ตรวจสอบ while (a < 20) | 16 | True - รอบถัดไป |
⚠️ ข้อผิดพลาดทั่วไป: Infinite Loop
// ผิด! ลืมเพิ่ม Counter ก่อน Continue
while (a < 20)
{
if (a == 15)
continue; // Infinite Loop! a ไม่เปลี่ยน เงื่อนไข while True ตลอด
Console.WriteLine(a);
a++;
}กฎข้อแม่: ใน while / do-while ต้อง Update Loop Variable ก่อน continue เสมอ
Continue ใน For Loop (ปลอดภัยกว่า)
for (int i = 10; i < 20; i++)
{
if (i == 15) continue; // i++ ทำงานอัตโนมัติแม้ Continue
Console.WriteLine(i);
}
// ไม่มี Infinite Loop เพราะ i++ รันหลัง Continue เสมอกรณีการใช้งานจริง (Use Cases)
- Input Validation: ข้ามข้อมูลไม่ถูกต้อง
- Filter Processing: ประมวลผลเฉพาะรายการที่ผ่านเกณฑ์
- Search Early Continue: หาเจอแล้วข้ามที่เหลือ (แต่ Break ดีกว่า)
// ตัวอย่าง: ประมวลผลเฉพาะเลขคู่
for (int i = 1; i <= 10; i++)
{
if (i % 2 != 0) continue; // ข้ามเลขคี่
Console.WriteLine(i * 2); // ประมวลผลเลขคู่
}ข้อสังเกตสำคัญ
continueใช้ได้ในfor,while,do-while,foreach- ใน
for- Iterator (i++) รันหลัง Continue เสมอ (ปลอดภัย) - ใน
while/do-while- ต้อง Update Variable เองก่อน Continue - ใน
foreach- ไปยัง Element ถัดไปทันที - ใช้
continueเพื่อลด Nested If (Flatten Code) - Guard Clause Pattern