Parameter Array (params) ใน C#
คีย์เวิร์ด params ช่วยให้เมธอดรับจำนวนอาร์กิวเมนต์ที่ไม่คงได้ (variable number of arguments) โดยรวบรวมเป็นอาร์เรย์อัตโนมัติ ทำให้เรียกใช้เมธอดสะดวกขึ้น ไม่ต้องสร้างอาร์เรย์ด้วยตนเอง
ไวยากรณ์
public ReturnType MethodName(params Type[] parameterName)
{
// parameterName เป็นอาร์เรย์ภายในเมธอด
}
กฎการใช้งาน
paramsต้องเป็นพารามิเตอร์ตัวสุดท้ายเท่านั้น- มีได้เพียงหนึ่ง
paramsต่อเมธอด - สามารถส่งอาร์เรย์โดยตรง หรือส่งค่าแยกต่างหากได้
- หากไม่ส่งอาร์กิวเมนต์ จะได้อาร์เรย์ว่าง (length = 0) ไม่ใช่ null
ตัวอย่างโค้ดสมบูรณ์
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("ผลรวม: {0}", sum1); // 1620
// เรียกใช้ส่งอาร์เรย์โดยตรง
int[] numbers = { 10, 20, 30 };
int sum2 = app.AddElements(numbers);
Console.WriteLine("ผลรวม: {0}", sum2); // 60
// ไม่ส่งอาร์กิวเมนต์
int sum3 = app.AddElements();
Console.WriteLine("ผลรวม: {0}", sum3); // 0
Console.ReadKey();
}
}
}
ผลลัพธ์
ผลรวม: 1620
ผลรวม: 60
ผลรวม: 0
params กับ IEnumerable และ Span (C# 13+)
// C# 13: params รองรับ IEnumerable และ ReadOnlySpan
public void Process(params IEnumerable numbers) { ... }
public void Process(params ReadOnlySpan numbers) { ... }
แนวทางปฏิบัติที่ดี
- ใช้เมื่อจำนวนพารามิเตอร์ไม่แน่นอนแต่ชนิดข้อมูลเหมือนกัน
- หลีกเลี่ยงการใช้กับประเภทข้อมูลที่ต่างกัน (ใช้
params object[]แทน แต่ต้องระวัง boxing) - พิจารณา overload เมธอดสำหรับกรณีที่ใช้บ่อย (เช่น 0, 1, 2 พารามิเตอร์) เพื่อประสิทธิภาพ
- เอกสาร化 พารามิเตอร์ params ให้ชัดเจนใน XML comments