Generic Types and Constraints
Question
Describe generic types and the generic type constraints you know.
Short interview answer
Generics let one type or method work with many types while preserving compile-time type safety. Constraints limit acceptable type arguments, for example
class,struct,new(), a base class, an interface,unmanaged,Enum, orDelegate.
Detailed answer
List<T> is a common example: List<int> accepts integers without runtime casts or boxing. Constraints express requirements needed by the implementation. For example, where T : IComparable<T> permits CompareTo, and where T : new() permits new T(). Static fields in a generic class belong to each closed constructed type, so Cache<int> and Cache<string> have separate static state.