Method Overloading (Nạp chồng phương thức) cho phép định nghĩa nhiều phương thức cùng tên nhưng khác signature (chữ ký) trong cùng một lớp. Trình biên dịch quyết định gọi phương thức nào dựa trên đối số truyền vào (compile-time polymorphism / static binding).
2 cách tạo overload
- Khác kiểu dữ liệu tham số (Different parameter types)
- Khác số lượng tham số (Different number of parameters)
Lưu ý: Chỉ khác kiểu trả về (return type) KHÔNG tạo thành overload.
Ví dụ 1: Khác kiểu dữ liệu
using System;
class Printer
{
public void Print(int i)
=> Console.WriteLine($"Integer: {i}");
public void Print(double d)
=> Console.WriteLine($"Double: {d}");
public void Print(string s)
=> Console.WriteLine($"String: {s}");
public void Print(bool b)
=> Console.WriteLine($"Boolean: {b}");
public void Print(int[] arr)
=> Console.WriteLine($"Array: [{string.Join(", ", arr)}]");
}
class Program
{
static void Main()
{
Printer p = new Printer();
p.Print(42);
p.Print(3.14);
p.Print("Hello");
p.Print(true);
p.Print(new[] { 1, 2, 3 });
}
}
Ví dụ 2: Khác số lượng tham số
using System;
class Calculator
{
public int Mul(int a, int b)
=> a * b;
public int Mul(int a, int b, int c)
=> a * b * c;
public int Mul(int a, int b, int c, int d)
=> a * b * c * d;
// C# 4.0+: Optional parameters thay thế một số overload
public int Mul(int a, int b, int c = 1, int d = 1)
=> a * b * c * d;
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine(calc.Mul(2, 3)); // 6
Console.WriteLine(calc.Mul(2, 3, 4)); // 24
Console.WriteLine(calc.Mul(2, 3, 4, 5)); // 120
// Với optional params:
Console.WriteLine(calc.Mul(2, 3, 4)); // 24 (d=1 mặc định)
}
}
Quy tắc phân giải Overload (Overload Resolution)
- Khớp chính xác (Exact match) → Ưu tiên cao nhất.
- Chuyển đổi ngầm (Implicit conversion):
int → long → float → double,derived → base. - Params array:
params int[](ưu tiên thấp hơn params cố định). - Generic method vs Non-generic: Non-generic ưu tiên hơn nếu cùng signature.
Best Practices
- Dùng optional parameters (C# 4+) thay vì nhiều overload cho tham số tùy chọn.
- Dùng named arguments để rõ ràng:
Mul(a: 2, c: 3, b: 4). - Tránh overload gây nhầm lẫn (ví dụ:
void Foo(int x)vàvoid Foo(double x)gọi vớiFoo(5)sẽ chọnint). - XML Documentation (
///) cho từng overload.