ภาพรวม
Nested If Statements คือ การวางคำสั่ง if หรือ else if ภายในอีก if หรือ else if ใช้เมื่อต้องการตรวจสอบเงื่อนไขหลายระดับ (Hierarchical Conditions)
ไวยากรณ์
if (boolean_expression_1)
{
// รันเมื่อเงื่อนไข 1 จริง
if (boolean_expression_2)
{
// รันเมื่อเงื่อนไข 1 และ 2 จริงทั้งคู่
}
}ตัวอย่างโปรแกรม
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
int a = 5;
int b = 10;
// ตรวจสอบเงื่อนไขระดับ 1
if (a == 5)
{
// ถ้า a == 5 จริง ให้ตรวจสอบเงื่อนไขระดับ 2
if (b == 10)
{
// ถ้า b == 10 จริงด้วย
Console.WriteLine("ค่าของ a คือ 5 และ b คือ 10");
}
}
Console.WriteLine("ค่าที่แท้จริงของ a: {0}", a);
Console.WriteLine("ค่าที่แท้จริงของ b: {0}", b);
Console.ReadLine();
}
}
}ผลลัพธ์
ค่าของ a คือ 5 และ b คือ 10 ค่าที่แท้จริงของ a: 5 ค่าที่แท้จริงของ b: 10
รูปแบบต่างๆ ของ Nested If
1. If ภายใน If (พื้นฐาน)
if (condition1)
{
if (condition2)
{
// ทั้งสองจริง
}
}2. If-Else ภายใน If
if (score >= 50)
{
if (score >= 80)
Console.WriteLine("Grade A");
else if (score >= 70)
Console.WriteLine("Grade B");
else
Console.WriteLine("Grade C");
}
else
{
Console.WriteLine("Fail");
}3. Multiple Levels (หลายระดับ)
if (user != null)
{
if (user.IsActive)
{
if (user.HasPermission("Admin"))
{
// Admin access
}
else if (user.HasPermission("User"))
{
// User access
}
}
}Best Practices: หลีกเลี่ยง Nested If ลึกเกินไป (Arrow Code)
ปัญหา: Arrow Code / Pyramid of Doom
// ยากต่อการอ่าน
if (a)
if (b)
if (c)
if (d)
DoSomething();แก้ไขด้วย Guard Clauses (Early Return)
// อ่านง่ายกว่า if (!a) return; if (!b) return; if (!c) return; if (!d) return; DoSomething();
แก้ไขด้วย Pattern Matching (C# 7+)
// สำหรับ Type Checking
if (obj is Student s && s.Grade >= 80 && s.Age > 18)
{
// ...
}แก้ไขด้วย Logical AND (&&)
// แทน Nested If ที่ไม่มี Else
if (a == 5 && b == 10)
{
Console.WriteLine("a=5 และ b=10");
}ข้อสังเกตสำคัญ
- Nested If เหมาะสำหรับเงื่อนไขที่ขึ้นกันจริง (Hierarchical Dependency)
- หลีกเลี่ยง Nesting ลึกเกิน 3-4 ระดับ → Refactor เป็น Method แยก หรือ Guard Clauses
- ใช้
&&(Short-circuit AND) แทน Nested If เมื่อเป็นแค่การตรวจสอบเงื่อนไขร่วมกัน - Indentation (เยื้อง) สำคัญมากสำหรับความอ่านง่าย
- Curly Braces
{ }ควรใช้เสมอแม้ Statement เดียว เพื่อป้องกัน Bug เมื่อเพิ่มโค้ดภายหลัง