skip to content

Type Parameters and Variance

Generic types and methods, constraints, variance and static abstract members: reusable, type-safe C# without boxing. Interviewers ask about variance and constraints.

on this pageshow

explore

questions

22

In a C# generic Repository<TEntity, TKey>, why does `new TEntity()` fail to compile, and what do where-clause constraints unlock?

level: juniorimportance: must knowfreq 70%

answer

  1. what the compiler may assume about T
  2. System.Object as the starting point
  3. a promise checked at every call site
  4. new(), base class, interface

basics

~20 s

An 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 s

Inside 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 lines
csharp
var 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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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.
open as a page

In C#, what does `default(T)` produce inside a generic method for `int`, `string`, `int?` and a struct, and why won't `return null;` compile?

level: juniorimportance: must knowfreq 60%

basics

~20 s

default(T) is the zero value of whatever type T is closed over: 0 for int, null for string and int?, a struct with every field zeroed. return null fails with CS0403 because T might be a non-nullable value type.

open as a page

In C#, why can a List<OrderPlaced> be passed as IEnumerable<DomainEvent> but not assigned to a List<DomainEvent>?

level: juniorimportance: must knowfreq 72%

basics

~10 s

IEnumerable<T> declares T as out (covariant) and only hands values out, so OrderPlaced items read safely as DomainEvent. List<T> is a class, classes are always invariant, and its Add(T) would otherwise accept any DomainEvent.

open as a page

In C#, why do `typeof(T)` and `value is List<T>` work inside a generic method, and how does `typeof(List<>)` differ from `typeof(List<int>)`?

level: middleimportance: must knowfreq 58%

basics

~20 s

C# generics are reified: each closed type such as List<string> carries its type argument at run time, so typeof(T) and is List<T> see the real argument. typeof(List<>) is the open generic type definition; typeof(List<int>) is one closed type built from it.

open as a page

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%

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.

open as a page

In C#, what does `where T : unmanaged` guarantee that `where T : struct` does not, when copying rows into a byte buffer?

level: middleimportance: should knowfreq 40%

basics

~20 s

struct only promises a non-nullable value type, which may still contain references such as a string field. unmanaged also requires every field, at any depth, to be unmanaged, so stackalloc T[n] compiles and a string-holding row fails with CS8377.

open as a page

In C#, how does IParsable<T> let a generic ParseSamples<T>(string[] cells) parse int, double or decimal statistics samples, and what must it pass?

level: middleimportance: should knowfreq 35%

basics

~10 s

IParsable<T> (.NET 7) declares static abstract Parse(string, IFormatProvider?) and TryParse, so ParseSamples<T> calls T.Parse(cell, provider) and each type parses itself. For machine data it must pass CultureInfo.InvariantCulture: a null provider means the current culture.

open as a page

In C#, what problem do static abstract interface members solve, and how does a generic Mean<T> where T : INumber<T> use them?

level: middleimportance: should knowfreq 48%

basics

~20 s

Before C# 11, an interface could require only instance members, so generic code could not use operators or static factories on T. Static abstract members (C# 11, .NET 7) let INumber<T> require them, so Mean<T> can write T.Zero, sum += v and T.CreateChecked(count).

open as a page

Why does the C# compiler report CS0411 for `int id = Wire.Decode(field);` when `Decode<T>(string field)` returns `T`, and what does inference use instead?

level: middleimportance: should knowfreq 50%

basics

~20 s

C# infers type arguments only from the arguments matched against parameter types, plus lambda return types and out variables. T appears only in Decode's return type, and neither the return type, the assignment target nor a constraint feeds inference, so it fails with CS0411.

open as a page

In C#, why do `MessageIds<Ping>.Id` and `MessageIds<Chat>.Id` read different values when the generic class declares a single static field?

level: middleimportance: should knowfreq 45%

basics

~20 s

Each closed constructed type, such as MessageIds<Ping> or MessageIds<Chat>, is a separate type to the CLR with its own copy of every static field and its own static constructor run, so one declaration yields one value per type argument.

open as a page

In C#, why can an IHandler<DomainEvent> declared with in TEvent be used where an IHandler<OrderPlaced> is required?

level: middleimportance: should knowfreq 48%

basics

~20 s

The in modifier makes TEvent contravariant: the handler only accepts events, and code that handles any DomainEvent can safely handle an OrderPlaced. The conversion runs from base to derived, as with Action<in T> and IComparer<in T>.

open as a page

In C#, why do `Save<T>(T item) where T : struct` and `Save<T>(T item) where T : class` in one class fail with CS0111?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Constraints are not part of a C# method signature, so both declare Save<T>(T) and the second is CS0111. Use different names, or put each in its own static class as an extension method; overload resolution discards a candidate whose constraint fails.

open as a page

In C# generic math, what do byte.CreateChecked, CreateSaturating and CreateTruncating return for 300, and which should Mean<T> use to convert its count?

level: seniorimportance: should knowfreq 28%

basics

~20 s

byte.CreateChecked(300) throws OverflowException, CreateSaturating(300) returns 255 and CreateTruncating(300) returns 44, the low eight bits. Mean<T> should use T.CreateChecked(values.Length): a count that does not fit in T is a bug, not a value to clamp or wrap.

open as a page

In C#, how do you let your own Money struct flow through a generic Sum<T>, and why constrain T to IAdditionOperators<T, T, T> rather than INumber<T>?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Implement the narrow interfaces the method needs, Money : IAdditionOperators<Money, Money, Money>, IAdditiveIdentity<Money, Money>, with a static operator + and AdditiveIdentity. INumber<T> would force about sixty members, including Parse and Money * Money, that money does not have.

open as a page

In C#, DomainEvent[] events = placed; compiles when placed is an OrderPlaced[], so why does storing an OrderCancelled into events throw?

level: seniorimportance: should knowfreq 45%

basics

~10 s

Arrays of reference types are covariant, so the assignment reuses the same OrderPlaced[] object. The runtime type-checks stores into it, and putting an OrderCancelled there throws ArrayTypeMismatchException at run time, not a compile error.

open as a page

In C#, why does interface IProducer<out TEvent> with a Publish(TEvent e) method fail with CS1961, and how do you fix it?

level: seniorimportance: should knowfreq 32%

basics

~20 s

A covariant (out) type parameter may appear only in output positions; a method parameter is an input position, so Publish(TEvent) gets CS1961. Split the interface into an out reading interface and an in writing interface.

open as a page

In C#, IEnumerable<T> is covariant, so why does a List<int> not convert to IEnumerable<object>?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Variance conversions are reference conversions that reuse the same object unchanged. Reading an int as object needs boxing, a new object per element, so variance applies only when the type argument is a reference type.

open as a page

As lead of a C# statistics package targeting netstandard2.0 and net8.0, would you replace its per-type Mean overloads with one INumber<T> generic method?

level: principalimportance: should knowfreq 22%

basics

~20 s

Not as a replacement. Keep the per-type overloads, which netstandard2.0 needs and compiled consumers bind to, and add a generic Mean on the net8.0 target only, with the narrowest constraints and an explicit result type, forwarding the old overloads to it.

open as a page

As lead of a shared C# events library, would you declare IProducer<TEvent> as out TEvent, knowing variance constrains every future member?

level: principalimportance: should knowfreq 20%

basics

~20 s

Declare out only for a pure producer that will stay one: callers gain free conversions, but no future member may take TEvent as input, and adding or removing out later changes overloads, type tests or compilation for callers.

open as a page

In C#, why does overriding `abstract void Record<T>(T? entry)` fail to compile unless the override adds `where T : default`?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

An override inherits its constraints, but the compiler reads T? in its own signature; with no clause that means Nullable<T>, so nothing matches (CS0453, CS0115). where T : default (C# 9) says the base T has neither class nor struct.

open as a page

In a C# generic Add<T> where T : IAdditionOperators<T, T, T>, why does checked(a + b) throw for int.MaxValue but wrap for a struct defining only operator +?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

In a checked context the compiler calls the checked operator +, a static virtual member of IAdditionOperators. int implements it with overflow-checked addition and throws OverflowException; a struct that defines only operator + gets the default body, which calls that unchecked operator and wraps.

open as a page

How does a C# static generic class such as `Codec<T>` act as a per-type cache without a `Dictionary<Type, T>`, and where does that idiom bite in production?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Each closed type such as Codec<Ping> has its own static field, initialized once under the runtime's per-type lock, so a lookup is a static field read. The costs: a throwing initializer stays broken, entries never evict, and the type must be a type argument.

open as a page