In a C# generic Repository<TEntity, TKey>, why does `new TEntity()` fail to compile, and what do where-clause constraints unlock?
answer
- what the compiler may assume about T
- System.Object as the starting point
- a promise checked at every call site
- new(), base class, interface
basics
~20 sAn unconstrained type parameter offers only System.Object's members, so new TEntity() fails with CS0304. A where clause adds guarantees: new() permits new T(), a base class or interface permits its members, and the compiler checks every type argument against them.
solid answer
~40 sInside a generic body the compiler may use only what the declaration promises. With no constraint, `TEntity` could be any type, so only `System.Object` members are available: `new TEntity()` is CS0304 and `entity.Id` is CS1061. Writing `where TEntity : Entity<TKey>, new()` and `where TKey : IComparable<TKey>` changes that: `new()` lets the body call `new TEntity()`, the base class lets it read `Id`, and the interface lets it call `CompareTo`. The cost moves to the call site: `Repository<Customer, int>` compiles only if `Customer` derives from `Entity<int>` (CS0311 otherwise) and has a public parameterless constructor (CS0310 otherwise). All of this is decided at compile time.
code
csharp · 30 linesvar repo = new Repository<Customer, int>();
Customer first = repo.Create(41);
Customer second = repo.Create(42);
Console.WriteLine(repo.Newer(first, second).Describe());
class Repository<TEntity, TKey>
where TEntity : Entity<TKey>, new()
where TKey : IComparable<TKey>
{
public TEntity Create(TKey id)
{
var entity = new TEntity(); // new(): CS0304 without it
entity.Id = id; // base class: CS1061 without it
return entity;
}
public TEntity Newer(TEntity a, TEntity b)
=> a.Id.CompareTo(b.Id) >= 0 ? a : b; // interface: IComparable<TKey>.CompareTo
}
abstract class Entity<TKey>
{
public TKey Id { get; set; } = default!;
public abstract string Describe();
}
class Customer : Entity<int>
{
public override string Describe() => $"customer {Id}";
}go deeper
Recall that an unconstrained T only has System.Object's members, and name the three everyday constraints: new() for new T(), a base class for its members, an interface for its methods.
Explain that the constraint is a two-sided contract checked at compile time: the body gains a capability, the caller must prove it, and the errors are CS0304 in the body and CS0310 or CS0311 at the call site.
Show where constraints stop: no constructor with arguments, no operators from interfaces, == meaning reference identity under class. Reach for a factory delegate when new() is not enough.
Treat every constraint on a shared generic type as a cost for all its callers; argue for the fewest constraints the body needs and for factories over new() when construction varies.
## What an unconstrained type parameter allows A **type parameter** such as `TEntity` in `Repository<TEntity, TKey>` is a placeholder the caller fills with a real type, the **type argument**. When the generic body is compiled, the compiler does not yet know which type that will be, so it lets the body do only what is legal for *every* possible type argument. With no constraint, that is very little: - call the members every type has through `System.Object`: `ToString()`, `Equals(object)`, `GetHashCode()`, `GetType()`; - assign values of type `T`, pass them around, store them in fields and collections; - compare a `T` with `null` (always false for a non-nullable value-type argument) and convert it to `object` or explicitly to an interface. Everything else is a compile error. `new TEntity()` is **CS0304** ("Cannot create an instance of the variable type 'T' because it does not have the new() constraint"), `entity.Id` is **CS1061**, and even `a == b` is **CS0019**, because not every type defines `==`. ## The capability constraints A `where` clause is a promise about the type argument. The compiler holds the caller to it and, in exchange, lets the body use what was promised. | Constraint | What the body gains | What the type argument must be | |---|---|---| | `new()` | `new T()` | non-abstract, with a public parameterless constructor | | a base class, e.g. `Entity<TKey>` | that class's accessible members | that class or a type derived from it | | an interface, e.g. `IComparable<TKey>` | that interface's members | a type implementing it (several interface constraints are allowed) | | `class` / `struct` | reference- or value-type operations, e.g. `T?` as `Nullable<T>` under `struct` | a reference type / a non-nullable value type | `struct` also implies `new()`, so `new T()` compiles under `struct` alone. ## A worked repository ```csharp class Repository<TEntity, TKey> where TEntity : Entity<TKey>, new() where TKey : IComparable<TKey> { public TEntity Create(TKey id) { var entity = new TEntity(); // allowed by new() entity.Id = id; // allowed by the base class return entity; } public TEntity Newer(TEntity a, TEntity b) => a.Id.CompareTo(b.Id) >= 0 ? a : b; // allowed by the interface } ``` Remove `new()` and `Create` fails with CS0304; remove the base class and `entity.Id` fails with CS1061; remove the interface and `CompareTo` fails with CS1061. Each constraint pays for exactly one capability. ## Checks at the call site The other half of the contract is enforced where the generic is used, also at compile time: 1. `new Repository<Report, int>()` where `Report` has only a constructor taking a `string` is **CS0310**: the type must be non-abstract with a public parameterless constructor. 2. `new Repository<Customer, int>()` where `Customer` does not derive from `Entity<int>` is **CS0311**: there is no implicit reference conversion to the base class. 3. A value type that fails a `class` constraint is **CS0452**; a reference type that fails `struct` is **CS0453**. For type arguments written in source, nothing is left for run time: once the program compiles, each of them has already been proven to satisfy the constraints. ## What constraints do not give you - **No constructor with arguments.** C# has only `new()`; there is no `new(int)` form. Pass a factory such as `Func<TKey, TEntity>` instead. The compiler turns `new T()` into a call to `Activator.CreateInstance<T>()`. - **No operators from an interface constraint.** `where T : IComparable<T>` gives `CompareTo`, not `<`; `where T : IEquatable<T>` gives `Equals(T)`, not `==` (still CS0019). Operators declared as static abstract interface members belong to the lesson on generic math. - **Some base classes are off limits.** `object`, `ValueType` and `Array` are **CS0702** ("Constraint cannot be special class 'object'", and the same for the other two); a sealed type such as `string` is **CS0701**. `System.Enum`, `System.Delegate` and `System.MulticastDelegate` have been allowed since C# 7.3. - **`where T : class` and `==`.** Under `class`, `==` compiles but compares references, even when the argument is `string`, whose own `==` compares contents. ## How to choose the constraints Start from the body, not from the domain model. List every operation the generic code performs on `T`, and add only the constraint that pays for each one: - the body creates instances: `new()`, or a factory parameter if construction needs arguments; - the body reads shared state or calls shared behaviour: a base class, when every type argument really is one; - the body needs a capability that unrelated types can share, such as ordering or disposal: an interface. Every constraint you add is one more thing each caller must satisfy, so a constraint the body never uses only narrows who can call it.
- In C#, how do you create a TEntity that needs constructor arguments, given that new() only covers a parameterless constructor?C# has no `new(int)` or similar constraint, only `new()`. Take a factory instead, for example a `Func<TKey, TEntity>` passed to the repository's constructor, and call it where you would have written `new TEntity(id)`. A base class with settable members plus `new()` is the other option. The compiler turns `new T()` into `Activator.CreateInstance<T>()`, which is all `new()` can ever reach.
- Can a C# constraint name System.Enum or System.Delegate as its base class?Yes, since C# 7.3: `where T : Enum`, `where T : Delegate` and `where T : MulticastDelegate` all compile. `where T : Enum` alone also accepts `System.Enum` itself, an abstract class, so enum helpers usually write `where T : struct, Enum` to get only concrete enum types. `object`, `ValueType` and `Array` are still rejected with CS0702.
- Does `where T : IEquatable<T>` let a C# generic method write `a == b`?No. An interface constraint gives the interface's instance members, so `a.Equals(b)` binds to `IEquatable<T>.Equals(T)`, but `a == b` is still CS0019. Operators reach generic code only through static abstract interface members, which is generic math. Under `where T : class`, `==` compiles but tests reference identity, not value equality.
- A type argument that breaks a constraint compiles and fails only when the method runs.
- An unconstrained T can call any public method; a missing member fails only at run time.
- The new() constraint lets the body call any constructor of T, including ones with parameters.
- where T : IEquatable<T> makes the == operator available on T.
- A base-class constraint may name object, ValueType or a sealed type such as string.