Method Overloading ใน C#
Method Overloading คือการประกาศเมธอดหลายตัวที่มี ชื่อเดียวกัน แต่ Parameter List ต่างกัน (จำนวน, ชนิด, ลำดับ) ใน Class เดียวกัน
วิธี Overload ได้ 2 แบบ
- จำนวนพารามิเตอร์ต่างกัน
- ชนิดข้อมูลพารามิเตอร์ต่างกัน
Return Type เพียงอย่างเดียว Overload ไม่ได้
ตัวอย่าง: จำนวนพารามิเตอร์ต่างกัน
public static int MulDisplay(int one, int two)
{
return one * two;
}
public static int MulDisplay(int one, int two, int three)
{
return one * two * three;
}
public static int MulDisplay(int one, int two, int three, int four)
{
return one * two * three * four;
}
ตัวอย่าง: ชนิดพารามิเตอร์ต่างกัน
void Print(int i) => Console.WriteLine($"Int: {i}");
void Print(double d) => Console.WriteLine($"Double: {d}");
void Print(string s) => Console.WriteLine($"String: {s}");
ตัวอย่างการเรียกใช้งาน
using System;
public class Demo
{
public static int MulDisplay(int one, int two) => one * two;
public static int MulDisplay(int one, int two, int three) => one * two * three;
public static int MulDisplay(int one, int two, int three, int four) => one * two * three * four;
}
public class Program
{
public static void Main()
{
Console.WriteLine("Two: " + Demo.MulDisplay(10, 15)); // 150
Console.WriteLine("Three: " + Demo.MulDisplay(8, 13, 20)); // 2080
Console.WriteLine("Four: " + Demo.MulDisplay(3, 7, 10, 7)); // 1470
}
}
ผลลัพธ์
Two: 150
Three: 2080
Four: 1470
Best Practices
- ใช้ Overloading เมื่อ Logic เหมือนกัน แค่ Input ต่างกัน
- หลีกเลี่ยง Overload มากเกินไป (Confusing) → ใช้ Optional Parameters หรือ
params - Optional Parameters (C# 4.0+):
void M(int a, int b = 10) - Named Arguments:
M(b: 5, a: 1)
Overloading vs Overriding
| Overloading | Overriding |
|---|---|
| Same Class | Derived Class Override Base |
| Different Signature | Same Signature |
| Compile-time (Static) | Run-time (Dynamic) |
| No Keyword Needed | Need virtual/override |