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?
answer
- all bits zero for the closed type
- value types versus reference types
- Nullable<int> with HasValue false
- CS0403 names its own fix
- EqualityComparer<T>.Default for comparing
basics
~20 sdefault(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 linesConsole.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
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.
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.
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.
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