Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Optional Parameters ใน C# คืออะไร และวิธีใช้

Optional Parameter คืออะไร?

Parameter ที่ ไม่บังคับ ต้องส่ง Argument ตอนเรียก Method มี Default Value ใน Definition

  • ไม่ส่ง Argument → ใช้ Default Value
  • ส่ง Argument → Override Default Value
  • ลด Overloading Method ลงได้

วิธีสร้าง Optional Parameter

1. Default Value (Standard Way - C# 4.0+)

public void Method(int required, int optional = 5) { ... }

// เรียกใช้
Method(10);        // optional = 5 (default)
Method(10, 20);    // optional = 20 (override)

2. [Optional] Attribute (COM Interop Legacy)

using System.Runtime.InteropServices;

public void Method(int required, [Optional] int optional) { ... }

// เรียกใช้
Method(10);        // optional = 0 (default ของ int)
Method(10, 20);    // optional = 20
⚠️ ไม่แนะนำ: [Optional] ไม่ได้ Set Default Value จริง ใช้ Default ของ Type (0, null, false) สับสนง่าย

ตัวอย่างครบถ้วน

using System;

namespace DemoApplication
{
    class Demo
    {
        static void Main(string[] args)
        {
            // ใช้ Default ทั้งคู่
            Calculate(10);
            
            // Override ค่าที่ 2
            Calculate(10, 20);
            
            // Named Parameter + Optional (ข้ามค่ากลางได้)
            Calculate(10, c: 30); // a=10, b=5(default), c=30
            
            Console.ReadLine();
        }

        // Optional Parameters ต้องอยู่ท้ายสุดเสมอ!
        public static void Calculate(int a, int b = 5, int c = 10)
        {
            Console.WriteLine($"a={a}, b={b}, c={c} => Sum = {a + b + c}");
        }
    }
}

Output

a=10, b=5, c=10 => Sum = 25
a=10, b=20, c=10 => Sum = 40
a=10, b=5, c=30 => Sum = 45

⚠️ กฎสำคัญ

  1. Optional Parameters ต้องอยู่ท้ายสุด - Required Parameters ต้องอยู่หน้า
  2. void Bad(int a = 5, int b) → Compile Error
  3. void Good(int a, int b = 5) → OK

Optional vs Method Overloading

Optional ParametersMethod Overloading
Syntax สั้น กระชับยาวกว่า แยก Method
Default Value แสดงใน SignatureDefault ซ่อนอยู่ใน Body
Binary Compatibility issue (DLL)Safe สำหรับ Public API
เหมาะ Internal/Private Methodเหมาะ Public Library API

Default Value ที่ซับซ้อน

// ใช้ Constant หรือ Parameterless Constructor เท่านั้น
void Method(DateTime date = default) { }           // OK: default(DateTime)
void Method(List<int> list = null) { }             // OK: null
void Method(string s = "default") { }              // OK: Constant

// ❌ Compile Error - ไม่ใช่ Constant
void Method(DateTime date = DateTime.Now) { }      
void Method(List<int> list = new List<int>()) { }