Parameter Arrays (params) ใน C#
params Keyword ใช้เมื่อไม่ทราบจำนวน Argument ล่วงหน้า ช่วยให้ส่ง Argument ได้หลายค่า หรือ Array ได้
ไวยากรณ์
returnType MethodName(params type[] parameterName)
{
// parameterName เป็น Array
}
ตัวอย่าง: Sum แบบ Param Array
using System;
namespace Program
{
class ParamArray
{
public int AddElements(params int[] arr)
{
int sum = 0;
foreach (int i in arr)
sum += i;
return sum;
}
}
class Demo
{
static void Main(string[] args)
{
ParamArray app = new ParamArray();
// ส่งเป็นรายตัว
int sum1 = app.AddElements(300, 250, 350, 600, 120);
Console.WriteLine($"Sum 1: {sum1}"); // 1620
// ส่งเป็น Array
int[] numbers = { 10, 20, 30 };
int sum2 = app.AddElements(numbers);
Console.WriteLine($"Sum 2: {sum2}"); // 60
// ส่ง 0 Argument
int sum3 = app.AddElements();
Console.WriteLine($"Sum 3: {sum3}"); // 0
Console.ReadKey();
}
}
}
ผลลัพธ์
Sum 1: 1620
Sum 2: 60
Sum 3: 0
กฎของ params
- ต้องเป็น **Parameter ตัวสุดท้าย** เท่านั้น
- มีได้ **เพียงหนึ่งตัว** ต่อ Method
- Type ต้องเป็น Single-dimensional Array (
int[],string[],object[]) - Caller ส่งได้ทั้ง Comma-separated Values และ Array
params กับ Object[] (รับ Type ใดก็ได้)
void PrintAll(params object[] items)
{
foreach (var item in items)
Console.WriteLine(item ?? "null");
}
// เรียก
PrintAll(1, "Hello", 3.14, true, null, new { Name = "Test" });
Performance Note
paramsสร้าง Array ใหม่ทุกครั้งที่เรียก (Allocation)- Hot Path: ใช้ Overloads สำหรับ Case ที่พบบ่อย (1, 2, 3 Args) + params สำหรับ General Case
- C# 10+:
params Span<T>หรือparams ReadOnlySpan<T>(No Allocation)
ตัวอย่าง Overload + params
public int Sum(int a) => a;
public int Sum(int a, int b) => a + b;
public int Sum(int a, int b, int c) => a + b + c;
public int Sum(params int[] args) => args.Sum(); // 4+ args