Why does C#'s `int? bonus = missing ? default : 5;` store 0 instead of null, and when do default and new() need a target?
answer
- the conditional is typed first
- the other branch decides
- default(T) with T inferred
- nothing to infer from with var
- C# 7.1 and C# 9
basics
~20 sIn missing ? default : 5, the int branch gives the conditional the natural type int, so default becomes 0 before the conversion to int?. The default literal and new() need a target type and fail without one, as with var.
solid answer
~50 sThe `default` literal (C# 7.1) is `default(T)` with `T` inferred from context, and target-typed `new()` (C# 9) is a constructor call whose type comes from the target. In `missing ? default : 5` the compiler first looks for a natural type for the whole conditional: `default` converts to `int`, so the expression is `int` and `default` is `0`; only then is the result converted to `int?`, so `bonus` holds `0` with `HasValue` true. C# 9 target typing of the conditional applies only when the branches have no natural type, as in `missing ? null : 5`, which yields `null`, as does `missing ? (int?)null : 5`. Neither shorthand works without a target: `var d = default;` is CS8716, `var r = new();` is CS8754, and `IList<int> ids = new();` is CS0144 because an interface cannot be instantiated.
code
csharp · 16 linesusing System;
using System.Collections.Generic;
bool missing = true;
int? fromDefault = missing ? default : 5;
int? fromNull = missing ? null : 5;
Console.WriteLine($"default branch: HasValue={fromDefault.HasValue}, value={fromDefault}");
Console.WriteLine($"null branch: HasValue={fromNull.HasValue}");
Dictionary<string, decimal> rates = new();
List<string> names = new() { "Ada", "Lin" };
Console.WriteLine($"{rates.Count} rates, {names.Count} names");
Pay(new(), default);
static void Pay(List<string> batch, decimal adjustment = default) =>
Console.WriteLine($"batch of {batch.Count}, adjustment {adjustment}");go deeper
Recall what default produces for numbers, bool, references and nullable types, and that the default literal and new() both need a target type to infer from.
Explain how a conditional expression gets its natural type before conversion, why missing ? default : 5 yields 0, and what CS8716, CS8754 and CS0144 report.
In review, spot default inside a conditional assigned to a nullable value, and rewrite it with null or default(int?) so the stored value matches the intent.
Agree a convention for when new() and the default literal help readability, such as fields and arguments, and when an explicit type or default(T) is clearer.
## The `default` literal `default(T)` produces the default value of a type: `0` for numeric types, `false` for `bool`, `null` for reference types and nullable value types, and an all-zero instance for other structs. Since **C# 7.1**, the **`default` literal** lets you drop `(T)` when the compiler can infer the type from context: the initialization or assignment of a variable, an optional parameter's default value, a method argument, or a `return` statement. `decimal adjustment = default;` is `0`; `string? note = default;` is `null`. ## Target-typed `new()` Since **C# 9**, a constructor call can omit the type name when the **target type** is known: `Dictionary<string, decimal> rates = new();` or `List<string> names = new() { "Ada", "Lin" };`. The parentheses are mandatory. It is the mirror image of `var`: with `var` the type is written on the right and inferred on the left; with `new()` it is written on the left and inferred on the right. It earns its keep where `var` is illegal, in fields such as `private readonly Dictionary<string, decimal> _rates = new();`, and in arguments such as `Pay(new(), default)`. ## Natural type first, target type second The surprise in `int? bonus = missing ? default : 5;` comes from the order in which the compiler types a conditional expression: 1. It first looks for a **natural type** from the two branches. `5` is an `int` and `default` can convert to `int`, so the natural type is `int`, and `default` becomes `default(int)`, which is `0`. 2. Only after the conditional has its type is the result converted to the target, `int?`. Converting `0` to `int?` gives a nullable that **has** a value. So `bonus` is `0` with `HasValue` true, not `null`. C# 9 added **target-typed conditional expressions**, but they apply only when the branches have **no** natural type, as in `missing ? null : 5`: `null` cannot become an `int`, so the compiler uses the target `int?` and the result is `null`. With `LangVersion` 8 that line is rejected with CS8957. | Expression assigned to `int?` | Natural type | Result when `missing` is true | |---|---|---| | `missing ? default : 5` | `int` | `0`, `HasValue` true | | `missing ? null : 5` | none, so the C# 9 target type `int?` is used | `null` | | `missing ? (int?)null : 5` | `int?` | `null` | | `missing ? default(int?) : 5` | `int?` | `null` | ## Where there is no target Both shorthands fail when nothing supplies a type: - `var d = default;` is **CS8716**: "There is no target type for the default literal." - `var r = new();` is **CS8754**: "There is no target type for 'new()'". - `IList<int> ids = new();` has a target, but it is an interface, so the SDK reports **CS0144**: "Cannot create an instance of the abstract type or interface 'IList<int>'". `new()` never picks an implementation for you. - An argument to a `dynamic` call is not a target either: `d.AddRange(new())` with a `dynamic` receiver is CS8754, because the parameter type is unknown until run time. ## Reviewing code that uses them - Prefer `new()` where the declared type sits on the same line: fields, auto-properties with initializers, and locals whose type you want written out. - Avoid the `default` literal as a branch of a conditional expression, or anywhere a natural type can win; write `null` or `default(int?)` so the intent survives. - Remember that `default` means `null` for a reference type and zero for a value type; when the target type is far away, the explicit `default(T)` tells the reader which one it is. - A `default` parameter value such as `decimal adjustment = default` is a compile-time constant like any other default parameter value, with the versioning consequences covered with optional parameters.
- Why is target-typed `new()` most useful on fields?Fields cannot use `var` (CS0825), so before C# 9 a field initializer had to repeat a long type: `private readonly Dictionary<string, decimal> _rates = new Dictionary<string, decimal>();`. With `new()` the type is written once, on the declaration: `private readonly Dictionary<string, decimal> _rates = new();`. The same applies to arguments whose parameter type is known, such as `Pay(new(), default)`.
- What does `return default;` return from a method declared to return `decimal`, and from one declared to return `string`?The `default` literal takes the method's return type as its target, so it returns `0` from the `decimal` method and `null` from the `string` method. The same word therefore means zero in one method and a null reference in another, which is why some teams prefer `default(T)` or an explicit `0m` or `null` where the return type is not visible nearby.
- default always means null
- missing ? default : 5 assigned to int? stores null
- var r = new(); creates an object
- IList<int> ids = new(); creates a List<int>
- C# 9 target typing makes every conditional take its assignment's type
- new() and var can be combined in one declaration