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

ชนิดของ Parameters ใน Method C# มีกี่แบบ

Parameter คืออะไร?

ค่าที่ส่งเข้า Method เพื่อให้ Method ทำงาน ตาม Signature ที่กำหนด

3 ประเภทหลัก

ประเภทKeywordทิศทางข้อมูลต้อง Initialize ก่อนส่งใช้เมื่อไหร่
Value Parameter(ไม่มี)In (Copy Value)YesGeneral, Primitive Types
Reference ParameterrefIn/Out (Reference)YesModify Caller's Variable
Output ParameteroutOut (Reference)No (Method ต้อง Assign)Return Multiple Values, Try Pattern

1. Value Parameters (Default)

Copy ค่าเข้า Parameter การเปลี่ยนแปลงใน Method ไม่ส่งผล กลับไป


void ModifyValue(int x)
{
    x = 10; // เปลี่ยน Local Copy เท่านั้น
}

int a = 5;
ModifyValue(a);
Console.WriteLine(a); // 5 (ไม่เปลี่ยน)

Output

Value before: x = 5
Sum = 20
Value after: x = 5

2. Reference Parameters (ref)

ส่ง Reference (Address) การเปลี่ยนแปลง ส่งผลกลับ ไปยัง Caller


void ModifyRef(ref int x)
{
    x = 10; // เปลี่ยนค่าจริงของ Caller
}

int a = 5;
ModifyRef(ref a);
Console.WriteLine(a); // 10 (เปลี่ยนแล้ว!)

Output

Value before: x = 5
Sum = 20
Value after: x = 10

3. Output Parameters (out)

คล้าย ref แต่:

  • ไม่ต้อง Initialize ก่อนส่ง
  • บังคับ Assign ค่าใน Method ทุก Path
  • ใช้สำหรับ Return Multiple Values / Try Pattern

void GetValues(out int x, out int y)
{
    x = 10; // ต้อง Assign
    y = 20; // ต้อง Assign
}

GetValues(out int a, out int b);
Console.WriteLine($"{a}, {b}"); // 10, 20

Output

Result: 20

เพิ่มเติม: in Parameter (C# 7.2+)

  • in = Read-only Reference
  • ส่ง Reference แต่ ห้าม Modify ใน Method
  • เหมาะสำหรับ Struct ใหญ่ (Avoid Copy) ที่ไม่ต้องการให้แก้ไข

void ReadOnly(in BigStruct data)
{
    // data.X = 10; // ❌ Compile Error
    Console.WriteLine(data.X); // ✅ Read Only
}

Params Parameter (Variable Arguments)


void PrintAll(params string[] names)
{
    foreach (var n in names) Console.WriteLine(n);
}

PrintAll("A", "B", "C"); // ส่งได้หลาย Argument
PrintAll(new[] { "X", "Y" }); // หรือส่ง Array

Optional Parameters (Default Value)


void Greet(string name, string greeting = "Hello")
{
    Console.WriteLine($"{greeting}, {name}!");
}

Greet("John");        // Hello, John!
Greet("John", "Hi");  // Hi, John!

สรุปการเลือกใช้

ต้องการอะไร?                    ใช้ตัวไหน?
────────────────────────────────────────────
ส่งค่าเข้า ใช้งานอย่างเดียว       Value Parameter (Default)
แก้ไขค่าตัวแปรของ Caller        ref
Return ค่าเพิ่ม (Multiple)       out
Try Pattern (bool + out)        out
Struct ใหญ่ Read-Only           in
จำนวน Argument ไม่แน่นอน        params
มี Default Value                Optional Parameter