C# รองรับ Overloading 2 รูปแบบ: Method Overloading และ Operator Overloading
1. Method Overloading
มีหลายเมธอดชื่อเดียวกัน แตกต่างใน จำนวนพารามิเตอร์ ประเภทพารามิเตอร์ หรือ ลำดับพารามิเตอร์ (Return type เพียงอย่างเดียว ไม่เพียงพอ)
ตัวอย่าง
public class Calculator {
public int Add(int a, int b) => a + b;
public int Add(int a, int b, int c) => a + b + c;
public double Add(double a, double b) => a + b;
public string Add(string a, string b) => a + b; // Concatenation
}
การเรียกใช้
var calc = new Calculator();
calc.Add(1, 2); // เรียก overload แรก
calc.Add(1, 2, 3); // เรียก overload ที่สอง
calc.Add(1.5, 2.5); // เรียก overload ที่สาม
calc.Add("Hello", "World"); // เรียก overload ที่สี่
2. Operator Overloading
กำหนดพฤติกรรมของ Operator (+, -, *, ==, !=, implicit, explicit, etc.) สำหรับ Custom Types
กฎ
- ต้องเป็น
public static - ต้องมี
operatorkeyword ตามด้วยสัญลักษณ์ Operator - อย่างน้อย 1 พารามิเตอร์ต้องเป็น Containing Type
- บาง Operator ต้อง Overloading คู่กัน (==, != / <, > / <=, >=)
ตัวอย่าง: Overload + สำหรับ Box
public class Box {
public double Length { get; set; }
public double Breadth { get; set; }
public double Height { get; set; }
public double Volume => Length * Breadth * Height;
// Overload + operator
public static Box operator +(Box b1, Box b2) {
return new Box {
Length = b1.Length + b2.Length,
Breadth = b1.Breadth + b2.Breadth,
Height = b1.Height + b2.Height
};
}
// Overload == และ != (ต้องเป็นคู่)
public static bool operator ==(Box b1, Box b2) {
if (ReferenceEquals(b1, null) && ReferenceEquals(b2, null)) return true;
if (ReferenceEquals(b1, null) || ReferenceEquals(b2, null)) return false;
return b1.Length == b2.Length && b1.Breadth == b2.Breadth && b1.Height == b2.Height;
}
public static bool operator !=(Box b1, Box b2) => !(b1 == b2);
// ต้อง Override Equals/GetHashCode ด้วยเมื่อ Overload ==/!=
public override bool Equals(object obj) => this == (obj as Box);
public override int GetHashCode() => (Length, Breadth, Height).GetHashCode();
}
การใช้งาน
var box1 = new Box { Length = 6, Breadth = 7, Height = 5 };
var box2 = new Box { Length = 12, Breadth = 13, Height = 10 };
var box3 = box1 + box2; // ใช้ Operator Overloading
Console.WriteLine($"Volume: {box3.Volume}"); // (6+12)*(7+13)*(5+10) = 18*20*15 = 5400
Operator ที่ Overload ได้ / ไม่ได้
| ได้ | ไม่ได้ |
|---|---|
| +, -, *, /, %, &, |, ^, <<, >> | =, &&, ||, ?:, new, typeof, sizeof |
| ==, !=, <, >, <=, >= | . (member access), () (cast - ใช้ explicit/implicit แทน) |
| ++, --, !, ~, true, false | |
| implicit, explicit (conversion) |
สรุป
- Method Overloading: เพิ่มความสะดวกในการเรียกใช้ API
- Operator Overloading: ทำให้ Custom Type ใช้งานเหมือน Primitive Type — ใช้เพียงพอ ไม่เกินจำเป็น
- Override Equals/GetHashCode เมื่อ Overload ==/!=