C# Interview Question #32

What are generic constraints in C#?

Generics & Collections Mid-Level Intermediate

Quick Interview Answer

Generic constraints restrict which types can be supplied for a generic type parameter. They allow generic code to safely use capabilities guaranteed by the constraint.

Detailed Explanation

Generic constraints restrict which types can be supplied for a generic type parameter. They allow generic code to safely use capabilities guaranteed by the constraint.

Common constraints include class, struct, notnull, unmanaged, new(), a specific base class, and one or more interfaces.

Constraints are declared with the where keyword.

Code Example

public T Create<T>() where T : class, new()
{
    return new T();
}

public void Save<T>(T entity) where T : IEntity
{
    // IEntity members can safely be used here.
}