Generics ช่วยให้คุณเขียนคลาสหรือเมธอดที่ทำงานกับชนิดข้อมูลได้ทุกประเภท โดยระบุพารามิเตอร์ชนิดข้อมูล (Type Parameter) แทนชนิดข้อมูลเฉพาะ
ประโยชน์ของ Generics
- เพิ่มการนำโค้ดกลับมาใช้ใหม่ (Code Reusability)
- เพิ่มความปลอดภัยของชนิดข้อมูล (Type Safety) - ตรวจสอบข้อผิดพลาดที่ compile-time
- เพิ่มประสิทธิภาพ (Performance) - หลีกเลี่ยง boxing/unboxing
- สร้าง Generic Collection Classes ได้ ใช้ namespace
System.Collections.Generic - สร้าง Generic Interfaces, Classes, Methods, Events, Delegates ได้
- รองรับ Constraints เพื่อจำกัดชนิดข้อมูลที่ใช้ได้
- รองรับ Reflection เพื่อตรวจสอบชนิดข้อมูลใน runtime
ตัวอย่าง Generic Class
public class GenericList<T>
{
public void Add(T input) { }
}
class Program
{
static void Main()
{
GenericList<int> list1 = new GenericList<int>();
GenericList<string> list2 = new GenericList<string>();
}
}
Generic Method
public void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}