skip to content

In C#, why does `where T : new(), class` fail to compile, and in what order must a type parameter's constraints appear?

level: middleimportance: should knowfreq 45%

answer

  1. three slots, fixed order
  2. one primary constraint at the front
  3. interfaces in the middle
  4. CS0401 and CS0449

basics

~20 s

C# fixes the order: one primary constraint first (a base class, or one of class, class?, struct, unmanaged, notnull), then interfaces and type parameters, then new() last. new(), class breaks both rules: CS0401 and CS0449.

solid answer

~40 s

Each type parameter's list has three slots in a fixed order. First, at most one primary constraint: a base class, or one of `class`, `class?`, `struct`, `unmanaged`, `notnull` (and `default`, only on overrides and explicit interface implementations). Then any number of interfaces and other type parameters. Then `new()`, last (CS0401 otherwise). Some pairs also exclude each other: `struct` already implies `new()` (CS0451), `unmanaged` implies `struct` and refuses `new()` (CS8375), and a base class cannot sit beside `class` or `struct` (CS0450). Constraints do not flow down to a derived generic type either: `class Audited<T> : Repository<T>` must repeat whatever makes `T` a valid argument for the base, or it is CS0314 or CS0310.

code

csharp · 13 lines
csharp
Console.WriteLine("constraint order");

class Repository<TEntity, TKey>
    where TEntity : new(), class           // new() first, class second
    where TKey : IComparable<TKey>, struct // struct after an interface
{
}

class FixedRepository<TEntity, TKey>
    where TEntity : class, new()
    where TKey : struct, IComparable<TKey>
{
}

go deeper

for a junior

Recall the order: class or struct (or a base class) first, interfaces next, new() last, and that the compiler rejects rather than reorders.

for a middle

Explain the three slots, which constraints imply others (struct implies new(), unmanaged implies struct) and the diagnostics each mistake produces: CS0401, CS0449, CS0450, CS0451.

for a senior

Show the inheritance rules: derived generic types restate constraints (CS0314, CS0310) while overrides inherit them (CS0460), and know that notnull and class mismatches are only warnings.

for a principal

Use the warning-only nature of notnull and class nullability checks to argue for warnings as errors in shared libraries whose generic APIs depend on them.

## The three slots The C# grammar gives every type parameter a constraint list in a fixed shape, and the compiler rejects anything out of order rather than sorting it: 1. **Primary constraint**, at most one, first: a **base class** (`Entity`, or `Entity?` for nullable arguments) or one of the keywords `class`, `class?`, `struct`, `unmanaged`, `notnull`. The keyword `default` also lives here, but only on overrides and explicit interface implementations. 2. **Secondary constraints**, any number: interfaces (`IComparable<T>`, `IDisposable`) and other type parameters (`where T : U`). 3. **Constructor constraint**, `new()`, last. The C# 13 `allows ref struct` anti-constraint, covered with ref structs, may only follow all of these. So `where T : new(), class` breaks two rules at once, and the SDK reports both: - **CS0401**: "The new() constraint must be the last restrictive constraint specified". - **CS0449**: "The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list." A base class written after an interface is **CS0406** ("The class type constraint 'Stream' must come before any other constraints"). ## Combinations that are rejected Some constraints already include others, or contradict them: | Written | Diagnostic | Why | |---|---|---| | `struct, new()` | CS0451 | every value type has a parameterless constructor, so `struct` already implies `new()` | | `unmanaged, new()` | CS8375 | `unmanaged` implies `struct`, and so `new()` | | `struct, unmanaged` or `class, struct` | CS0449 | only one keyword fits the primary slot | | `Stream, class` | CS0450 | a base class already decides reference vs value | | `object`, `ValueType`, `Array` as base | CS0702 | special classes cannot be constraints | The rules leave plenty that does combine: `where T : class, IDisposable, new()`, `where T : struct, IComparable<T>`, `where T : Entity, IAuditable, new()`, or `where T : unmanaged, IEquatable<T>`. ## The primary slot under nullable reference types With nullable reference types enabled, the primary keyword also says whether a nullable argument is welcome. Nullability mismatches are **warnings**, not errors, and they appear only in a nullable context; the `struct` row is an error because `string?` is not a value type at all: | Constraint | Accepts | Passing `string?` | |---|---|---| | `class` | non-nullable reference types | warning CS8634 | | `class?` | nullable or non-nullable reference types | no diagnostic | | `notnull` | non-nullable reference or value types | warning CS8714 | | `struct` | non-nullable value types (so not `int?`) | error CS0453 | `Dictionary<TKey,TValue>` declares `where TKey : notnull`, which is why `new Dictionary<string?, int>()` warns rather than fails. ## Constraints and inheritance Two inheritance rules trip people up, and they point in opposite directions: - **Generic types do not inherit constraints.** If `Repository<TEntity>` declares `where TEntity : Entity, new()`, then `class AuditedRepository<TEntity> : Repository<TEntity>` must restate both. Leave out the base class and the SDK reports CS0314; leave out `new()` and it reports CS0310. The derived type's own `TEntity` must provably satisfy the base type's constraints. - **Overriding methods do inherit them.** An `override` or explicit interface implementation takes its constraints from the base method and may not restate them: writing `where T : IDisposable, new()` on an override is **CS0460**. Only `class` or `struct` (and, since C# 9, `default`) may be written there, because they change what `T?` means in the override's signature. ## Reading a constraint list in review A practical habit when a generic declaration fails to compile: - read each `where` clause left to right and check it lands in the slots in order; - look for a keyword that already implies another (`struct` and `new()`, `unmanaged` and `struct`); - check that a derived generic type repeats its base type's constraints; - remember that a nullable mismatch on `notnull` or `class` is a warning, so it can slip through a build that does not treat warnings as errors. Most of these mistakes come from writing constraints in the order you thought of them, for example adding `class` after an interface because the reference-type requirement came up later in design. The fix is always mechanical: move the primary constraint to the front, `new()` to the end, and delete any keyword another one already implies.

  • In C#, `Repository<TEntity>` declares `where TEntity : Entity, new()`; what must `class AuditedRepository<TEntity> : Repository<TEntity>` declare?
    It must restate `where TEntity : Entity, new()`. A derived generic type does not inherit its base type's constraints; its own type parameter has to satisfy them. Leaving out the base class gives CS0314, leaving out `new()` gives CS0310. Overriding methods are the opposite case: they inherit their base method's constraints and may not restate them (CS0460).
  • In C#, why are `where T : struct, new()` and `where T : unmanaged, new()` rejected?
    `struct` already guarantees a parameterless constructor, because every value type has one, so `new()` beside it is CS0451, and `new T()` compiles under `struct` alone. `unmanaged` implies `struct`, so `new()` beside it is CS8375, and `struct, unmanaged` is CS0449 because both want the single primary slot.
  • With nullable reference types on, what happens when a C# caller passes `string?` to `where T : notnull` or to `where T : class`?
    Both produce warnings, not errors: CS8714 for `notnull` and CS8634 for `class`, and the program still builds. `class?` accepts `string?` with no diagnostic. In a nullable-oblivious context neither check reports anything. Teams that need these to stop the build turn on warnings as errors.

  • The compiler sorts constraints itself, so their order in the where clause does not matter.
  • A value type needs where T : struct, new() before the body can call new T().
  • Writing class next to a base-class constraint documents that the argument is a reference type.
  • Passing string? to a notnull constraint is a compile error.
  • A derived generic class inherits its base class's type-parameter constraints automatically.