C# generics and type constraints (where T : class, struct, new()) explained

C# Language Interview Q&A November 13, 2026 csharp

Type safety without casting, without boxing, and code reuse.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// ======================================================================
// Q: Generics and constraints: why and how?
//
// Type safety without casting, without boxing, and code reuse. Constraints state
// what the code is allowed to do with T.
// ======================================================================

public interface IEntity { int Id { get; } }

public class Cache<T> where T : class, IEntity      // reference type that has an Id
{
    private readonly Dictionary<int, T> _items = new();
    public void Add(T item) => _items[item.Id] = item;
    public T? Get(int id) => _items.GetValueOrDefault(id);
}
// Other constraints: struct, new(), notnull, unmanaged, where T : BaseClass