skip to content

Reified Generics

Generic types are reified by the CLR, each closed type gets its own statics, and methods infer type arguments. Interviewers compare this with erased generics.

on this pageshow

explore

questions

5

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%

answer

  1. all bits zero for the closed type
  2. value types versus reference types
  3. Nullable<int> with HasValue false
  4. CS0403 names its own fix
  5. EqualityComparer<T>.Default for comparing

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.

solid answer

~40 s

`default(T)`, or the `default` literal where the type can be inferred, yields the default value of the type argument the method was called with: `0` for `int`, `null` for a reference type such as `string`, `null` for `int?` (a `Nullable<int>` whose `HasValue` is `false`), and for a struct an instance with every field zeroed and no constructor run. Because C# keeps type arguments at run time, one method body returns a different value for each closed type. `return null;` is rejected with CS0403 since an unconstrained `T` could be a non-nullable value type, and the message itself suggests `default(T)`. For the same reason `value == default` fails with CS8761, so compare through `EqualityComparer<T>.Default.Equals(value, default)`.

code

csharp · 8 lines
csharp
Console.WriteLine(Describe<int>());
Console.WriteLine(Describe<string>());
Console.WriteLine(Describe<int?>());
Console.WriteLine(Describe<Move>());

static string Describe<T>() => $"{typeof(T).Name}: {default(T)?.ToString() ?? "null"}";

record struct Move(int X, int Y);

go deeper

for a junior

Recall the table: zero for numbers, false for bool, null for references and Nullable<T>, zeroed fields for structs, and default(T) as the fix CS0403 suggests.

for a middle

Explain why the compiler rejects null, == default and a == b for an unconstrained T, and show EqualityComparer<T>.Default.Equals(value, default) as the general comparison.

for a senior

Point out where a default value is ambiguous with real data, such as FirstOrDefault on a list of ints, and prefer Try-pattern methods that return a bool beside the value.

for a principal

Frame default(T) as an API contract choice: whether a generic API signals absence through default, a bool or an explicit fallback argument shapes every caller.

## What `default(T)` means A **generic method** such as `static T Reset<T>()` is written once against a **type parameter** `T`. Each call supplies a **type argument** (`int`, `string`, a struct), and the method then runs as that **closed type**. Inside the body you often need "the empty value of whatever `T` is": the result of a failed lookup, the initial value of an accumulator, a slot that has not been filled yet. C# gives you that with the **`default` operator**, `default(T)`, and its shorter form, the **`default` literal** (`default` on its own), which the compiler accepts wherever it can infer the target type: a variable initializer, a `return` statement, an argument, an optional parameter's default. Both produce the **default value** of the type: the value whose storage is all zero bits. ## The value for each kind of type argument Because C# generics keep their type arguments at run time, the same compiled body produces a different value for each closed type: | Type argument | `default(T)` | Why | |---|---|---| | `int`, `double`, `bool`, an enum | `0`, `0.0`, `false`, the enum's zero value | value types, all bits zero | | `string`, a class, an interface, a delegate, an array | `null` | a reference type's zero is the null reference | | `int?` (`Nullable<int>`) | `null`, meaning `HasValue` is `false` | `Nullable<T>` is a struct whose zeroed form is "no value" | | a struct such as `record struct Move(int X, int Y)` | an instance with every field at its own default | no constructor runs, the fields are just zeroed | Two consequences matter in practice: - **No constructor runs.** For a struct, `default(T)` ignores any constructor or field initializer you wrote; you get zeroed fields, not "a sensible empty instance". - **The default can be a legitimate value.** For `int`, `0` is both "nothing found" and a real result. The BCL accepts that: `Dictionary<TKey,TValue>.TryGetValue` sets its `out` value to `default` when the key is missing and tells you via its `bool` result, and `Enumerable.FirstOrDefault` on an empty `List<int>` returns `0`, which a caller cannot tell apart from a stored zero. ## Why `null` and `== default` are rejected for an unconstrained `T` An **unconstrained** `T` may be closed over a value type or a reference type, so the compiler only allows what is valid for both. The SDK reports these errors: 1. `return null;` gives **CS0403**: "Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead." The message itself names the fix. 2. `value == default` gives **CS8761**: the `==` operator cannot be applied to `default` and an operand of type `T` "because it is a type parameter that is not known to be a reference type". 3. `a == b` with two `T` operands gives **CS0019**: operator `==` cannot be applied to operands of type `T` and `T`, because not every type defines `==`. One test is special-cased: `value == null` **does compile** for an unconstrained `T`. When `T` is a non-nullable value type it is simply `false`; for a reference type or a `Nullable<T>` it is a real null test. ## Comparing a value with the default correctly To ask "is this still the default?" without knowing `T`, go through the type's own equality: - `EqualityComparer<T>.Default.Equals(value, default)` works for every `T`; it calls `IEquatable<T>.Equals` when the type implements that interface and falls back to `Object.Equals` otherwise. - `value is null` and `value == null` test only for null; for a non-nullable value type they are always `false`. - A `class` constraint would make `== null` and `return null` legal, but it shuts value types out; choosing constraints is a separate design decision. ## Where `default(T)` turns up in everyday code - **Try-pattern methods** assign `default` to the `out` parameter on failure, as `TryGetValue` does. - **`...OrDefault` operators** (`FirstOrDefault`, `LastOrDefault`, `SingleOrDefault`) return `default(TSource)` when there is no element, unless you call the overload that takes an explicit default value. - **New arrays and fields**: `new T[16]` holds sixteen `default(T)` values, and a field of type `T` starts as `default(T)` until it is assigned. - **Resetting a slot** in a pooled or ring buffer writes `default` so a reference-type element does not keep an object alive. A note on annotations: with nullable reference types on, returning `default` from a method declared to return `T` produces a nullable warning, because `default(T)` is `null` when `T` is a reference type; how `T?` and the flow-analysis attributes express that is part of the null-safety material, not of this question. ## Summary `default(T)` is the zero value of the closed type: `0`-like for value types, `null` for reference types and `Nullable<T>`, zeroed fields for structs. It exists precisely because `null`, `==` and `new T()` are not valid for every possible `T`, and it pairs with `EqualityComparer<T>.Default` whenever you need to compare against it.

  • Why can `FirstOrDefault` on a `List<int>` mislead a caller?
    On an empty sequence `FirstOrDefault` returns `default(int)`, which is `0`, and a list that really starts with `0` returns the same thing. The caller cannot tell 'no element' from 'element is zero'. Use the overload that takes an explicit default value, check `Count` or `Any()` first, or use a Try-style method that returns a `bool` beside the value, as `Dictionary<TKey,TValue>.TryGetValue` does.
  • Does `value == null` compile when `T` is unconstrained, and what does it do for an `int`?
    Yes. Comparing an unconstrained `T` with the `null` literal is special-cased: it compiles and, when `T` is a non-nullable value type such as `int`, it is always `false`. For a reference type or a `Nullable<T>` it is a genuine null test. What does not compile is `value == default` (CS8761) or `a == b` between two `T` values (CS0019).
  • What does `default(T)` give for a struct whose constructor sets fields to non-zero values?
    Zeroed fields. `default(T)` never runs a constructor or field initializer; it produces the struct's all-zero form, exactly like an element of a freshly created array. If the type needs a valid 'empty' instance, expose it explicitly, for example as a static property, rather than relying on `default`.

  • default(T) calls the type's parameterless constructor
  • default(T) is always null inside a generic method
  • return null works for any T if nullable is enabled
  • value == default is fine for an unconstrained T
  • default(int?) is 0 because the underlying type is int
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

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

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