How does the C# compiler decide the type of a switch expression whose arms return different types, such as an int and a null?
answer
- best common type of the arms
- falls back to the target
- var has no target
- a double hiding behind object
basics
~20 sA switch expression takes the best common type of its arms when one exists. Otherwise, as with an int arm and a null arm, it takes the type it is converted to; var supplies none, so the compiler reports CS8506.
solid answer
~50 sThe compiler first looks for a **natural type**: the best common type of the arm expressions, provided every arm converts to it implicitly, so arms of `1` and `2.5` give `double`. If there is no natural type, the switch expression is **target-typed**: it converts to any type `T` that every arm converts to, so `int? x = code switch { 1 => 10, _ => null }` and `object o = code switch { 1 => 1, _ => "many" }` both compile. `var` supplies no target, so those arms give error CS8506, "No best type was found for the switch expression." Both rules date from C# 8. The trap is that a natural type wins over the target: `object o = flag switch { true => 1, false => 2.5 }` boxes a `double` 1.0, not an `int`.
code
csharp · 10 linesbool exact = args.Length == 0;
object boxed = exact switch { true => 1, false => 2.5 };
Console.WriteLine(boxed.GetType().Name); // Double, not Int32
int code = 2;
int? surcharge = code switch { 1 => 10, _ => null }; // no natural type: target-typed to int?
object label = code switch { 1 => 1, _ => "many" }; // no natural type: target-typed to object
Console.WriteLine($"{surcharge is null} {label}"); // True many
// var bad = code switch { 1 => 1, _ => "many" }; // error CS8506: no best type, no targetgo deeper
Know that all arms of a switch expression must produce values of one type the compiler can work out.
Explain natural type versus target type, why var with an int and a null arm gives CS8506, and how a cast on one arm fixes it.
Catch the widening trap in review, where an object target boxes a double because another arm was a double.
Prefer arms that share a declared base type or interface over object-typed switches that hide what callers receive.
## Two ways a switch expression gets a type Every expression in C# needs a type, and a switch expression has several candidate results, one per arm. The C# 8 design that introduced switch expressions gave them two rules, applied in order: 1. **Natural type.** The compiler computes the **best common type** of the expressions to the right of the `=>` tokens. If such a type exists and every arm's expression converts implicitly to it, that is the switch expression's type. 2. **Target type.** If there is no natural type, the switch expression still compiles wherever it is **converted to** a type `T` such that every arm converts implicitly to `T`. The proposal calls this the *switch expression conversion*. If neither applies, the compiler reports **CS8506**: "No best type was found for the switch expression." ## The natural type in practice - `code switch { 1 => "one", _ => "many" }` has natural type `string`. - `code switch { 1 => 1, _ => 2.5 }` has natural type `double`: `int` converts implicitly to `double`, so `double` is the best common type and the `1` arm yields `1.0`. - An arm that is a **throw expression** has no type and does not take part; it converts to whatever the other arms decide. - A `null` literal has no type either. With `1` and `null`, the best common type candidate is `int`, but `null` does not convert to `int`, so there is **no** natural type. ## Target typing when the arms disagree When there is no natural type, the declared type of the destination decides: | Code | Natural type | Result | |---|---|---| | `int? x = code switch { 1 => 10, _ => null };` | none | compiles, type `int?` | | `object o = code switch { 1 => 1, _ => "many" };` | none | compiles, type `object` | | `var v = code switch { 1 => 1, _ => "many" };` | none | error CS8506 | | `var w = code switch { 1 => 1, _ => null };` | none | error CS8506 | | `var d = code switch { 1 => 1, _ => 2.5 };` | `double` | compiles, type `double` | The same applies to a method argument or a `return`: the parameter type or the return type is the target. A common belief is that target-typed switch expressions arrived in C# 9. They did not: the C# 8 proposal already defines the switch expression conversion, and the SDK accepts `int? x = code switch { 1 => 10, _ => null };` with `LangVersion` set to 8. What C# 9 added was target typing for the **conditional operator** `?:`. ## The trap: the natural type wins Target typing is only the fallback. When the arms have a natural type, the switch expression has that type, and the conversion to the target happens **after** the arm's value has been converted to the natural type: ```csharp object boxed = exact switch { true => 1, false => 2.5 }; Console.WriteLine(boxed.GetType().Name); // Double ``` The `true` arm's `1` is first converted to `double`, then boxed. Code that later tests `boxed is int` finds `false`. The same happens with `long` and `int` arms, `decimal` and `int` arms, and any pair where one arm's type converts implicitly to the other's. ## Making the type explicit When the intended type matters, state it rather than relying on inference: - Declare the variable with its type instead of `var`, so target typing applies when there is no natural type. - Cast one arm, for example `1 => (int?)10`, so the best common type becomes `int?` even with `var`. - When arms legitimately return unrelated types, the design is usually better served by a common base type or interface than by `object`. ## What to remember in an interview - Natural type first, target type second, CS8506 when both fail. - `null` and throw expressions do not contribute a type. - `var` never supplies a target. - A numeric widening between arms changes the value of every arm, not just the wider one. How implicit numeric conversions and boxing work in general is covered with operators and with boxing; this question is about how a switch expression picks its type.
- How do you make `var x = code switch { 1 => 10, _ => null };` compile?Give the arms a best common type: cast one arm, as in `1 => (int?)10` or `_ => (int?)null`, so `int?` becomes the natural type. Or drop `var` and declare `int? x`, so the switch expression is target-typed to `int?`.
- Does a throw expression arm affect the switch expression's type?No. A throw expression has no type, so it is ignored when the best common type is computed and converts to whatever type the other arms produce. A switch expression whose arms are all throw expressions has no natural type, and with `var` the compiler reports CS8506.
- Saying target-typed switch expressions arrived in C# 9
- Expecting var to infer object when arms return int and string
- Believing a target type of object keeps each arm's own type when the arms share a natural type
- Thinking a null arm alone makes the result nullable with var
- Counting a throw expression arm when working out the result type