params ใช้เมื่อจำนวน Arguments ไม่แน่ชัด — รับ Array ของ Arguments ได้หลายตัว
Syntax
ReturnType MethodName(params Type[] parameterName) { }
กฎ
paramsต้องเป็น **Parameter ตัวสุดท้าย** เท่านั้น- มีได้ **เพียง 1 params ต่อ Method**
- Array Type ต้องเป็น Single-dimensional
- Caller สามารถส่ง: Comma-separated Values, Array, หรือ ไม่ส่งเลย (Empty Array)
ตัวอย่างพื้นฐาน
using System;
class Calculator {
public int Add(params int[] numbers) {
int sum = 0;
foreach (int n in numbers) sum += n;
return sum;
}
}
class Program {
static void Main() {
var calc = new Calculator();
Console.WriteLine(calc.Add()); // 0 (Empty Array)
Console.WriteLine(calc.Add(1)); // 1
Console.WriteLine(calc.Add(1, 2, 3)); // 6
Console.WriteLine(calc.Add(1, 2, 3, 4, 5)); // 15
// ส่ง Array โดยตรง
int[] vals = { 10, 20, 30 };
Console.WriteLine(calc.Add(vals)); // 60
Console.ReadKey();
}
}
params กับ Overloading
class Printer {
// Specific Overloads (Preferred for Performance/Clarity)
public void Print(int value) => Console.WriteLine($"Int: {value}");
public void Print(int a, int b) => Console.WriteLine($"Two Ints: {a}, {b}");
// Params Catch-all
public void Print(params int[] values) {
Console.WriteLine("Array: " + string.Join(", ", values));
}
}
// Calls:
Print(1); // Specific: Print(int)
Print(1, 2); // Specific: Print(int, int)
Print(1, 2, 3); // Params: Print(params int[])
params IEnumerable<T> (C# 13 / .NET 9+)
// รองรับ IEnumerable โดยตรง ไม่ต้อง ToArray()
public void Process(params IEnumerable numbers) {
foreach (var n in numbers) Console.WriteLine(n);
}
// Call with Collection
Process(1, 2, 3);
Process(new List { 4, 5, 6 }); // No Allocation!
Performance Considerations
paramsสร้าง Array ใหม่ทุกครั้งที่เรียก (Allocation)- Hot Path: ใช้ Overloads สำหรับ 0-4 Arguments + params สำหรับ 5+
- C# 13:
params IEnumerable<T>ลด Allocation เมื่อส่ง Collection ที่มีอยู่แล้ว
ตัวอย่าง: String.Format / Console.WriteLine
Framework Methods ใช้ params อย่างกว้างขวาง:
Console.WriteLine("Sum: {0}, Count: {1}, Avg: {2}", sum, count, avg);
String.Format("{0} {1} {2}", "Hello", "World", "!");
// Signature: public static void WriteLine(string format, params object[] args)
สรุป
params= Variable Arguments สะดวกสำหรับ API ที่ยืดหยุ่น- วางตำแหน่งสุดท้าย, 1 ตัวต่อ Method
- Performance: Overload Specific Arities + params Fallback
- Modern:
params IEnumerable<T>(C# 13) ลด Allocation