C# where T: Generic Type Constraints Explained
Learn how the C# where T clause constrains generic type parameters, enables compile-time type safety, and covers common constraints like class, struct, new(), and interfaces.

In C#, the where T : ... clause constrains generic type parameters. It defines a contract that the compiler enforces: any type substituted for T must satisfy the specified constraint. That guarantee is the foundation of generic type safety, and it lets you write reusable code while still knowing which members are available at compile time.
The Basic Syntax of the where Clause
The where clause appears after the generic parameter list. For a generic class, it looks like this:
public class Repository<T> where T : IEntity
{
public T GetById(int id)
{
// ...
}
}For a method, the constraint is placed after the parameter list and before the body:
public T FindById<T>(int id) where T : IEntity
{
// ...
}The constraint can be a base class, an interface, another type parameter, or one of the special constraints class, struct, or new(). You can also combine multiple constraints, separated by commas. The new() constraint must appear last if it is used.
Common Type Constraints
The most frequently used constraints are summarized below:
| Constraint | Meaning |
|---|---|
where T : class | T must be a reference type: class, interface, delegate, or array. |
where T : struct | T must be a value type, excluding Nullable<T>. |
where T : new() | T must have a public parameterless constructor. |
where T : BaseClass | T must derive from BaseClass. |
where T : IInterface | T must implement IInterface. |
where T : U | T must be or derive from another generic parameter U. |
The class and struct constraints are mutually exclusive. The new() constraint is often combined with class or an interface, but it cannot be used with struct because all value types already have a parameterless constructor.
Applying Constraints to Methods and Classes
Constraints become valuable when you need to use members of the type parameter. For example, consider a validation class that requires a parameterless constructor and reference semantics:
public class Validator<T> where T : class, new()
{
public bool Validate(T entity)
{
if (entity == null) return false;
// Additional validation logic
return true;
}
}Here, class allows the null check, and new() lets you create a default instance if needed. Without the new() constraint, you cannot write new T() inside the generic class.
Another common pattern is constraining to an interface to call its methods:
public static T Max<T>(T left, T right) where T : IComparable<T>
{
return left.CompareTo(right) >= 0 ? left : right;
}The IComparable<T> constraint gives you access to CompareTo, which is essential for comparison logic.
How Constraints Affect Compile-Time Type Safety
The primary benefit of constraints is that they move type errors from runtime to compile time. If you try to use a type that does not satisfy the constraint, the compiler rejects the code immediately. For instance, calling Max with a type that does not implement IComparable<T> results in a compilation error.
Constraints also enable the compiler to resolve member access. Without a constraint, T is treated as having only the members of object, and you would need reflection or unsafe casting to call any specific member. Constraints eliminate that overhead and make the code self-documenting.
Runtime Behavior and Performance Considerations
Constraints are recorded as metadata on the generic type or method and are checked when generic code is compiled and when the runtime instantiates a closed generic type. For value types, the JIT typically generates specialized code, which can avoid boxing. For reference types, it can share the same generated code.
Over-constraining can limit reuse. For example, using where T : struct when you only need a parameterless constructor is more restrictive than necessary. Conversely, using where T : class when you need value types will prevent valid usage. The choice of constraint should be driven by the actual operations performed inside the generic code, not by a desire to be strict.
Common Mistakes and Edge Cases
A frequent mistake is forgetting the new() constraint when trying to instantiate T:
public T Create<T>()
{
return new T(); // Compiler error unless T has new() constraint
}Adding where T : new() fixes this, but remember that new() cannot be used with struct because all value types already have a parameterless constructor.
Another edge case is combining class and struct constraints, which is invalid. Also, when using multiple constraints, the new() constraint must be listed last.
A more subtle issue arises with nullable value types. The struct constraint excludes Nullable<T>, so where T : struct does not accept int?. If you need to allow nullable value types, you must design your API differently, for example by using where T : struct and handling nullability separately.
Choosing the Right Constraint for Your API
The decision of which constraint to apply depends on what your generic code actually needs. Use where T : class when you need reference semantics, such as null checks or identity comparisons. Use where T : struct when your logic requires a non-nullable value type. Use where T : new() when you need to create instances. Use an interface constraint when you need specific members, and a base class constraint when you want to share implementation.
Keep constraints as minimal as possible. The fewer restrictions you place on T, the more reusable your generic code becomes. If you find yourself adding many constraints, consider whether a non-generic interface or a base class would be a better design. Constraints are a tool for expressing requirements, not for artificially narrowing the set of acceptable types.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.