Generics cho phép viết class/method làm việc với bất kỳ kiểu dữ liệu nào.
Viết spec cho class/method với tham số thay thế kiểu dữ liệu. Compiler sinh code xử lý kiểu cụ thể khi gặp constructor/gọi hàm.
Lợi ích Generics:
- Tái sử dụng code, type safety, performance.
- Tạo generic collection classes. Thư viện .NET có generic collections trong
System.Collections.Genericthay choSystem.Collections. - Tự tạo generic interfaces, classes, methods, events, delegates.
- Generic classes constrained để truy cập method trên kiểu đặc định.
- Lấy thông tin kiểu tại runtime qua reflection.