skip to content

In C#, what type does a conditional expression like flag ? 1 : null get, and why can it not be a statement?

level: seniorimportance: should knowfreq 30%

answer

  1. natural type first, target type second
  2. C# 9 conditional expression conversion
  3. var has no target
  4. only some expressions are statements

basics

~20 s

A C# conditional expression takes its operands' common type; without one, C# 9 and later convert each operand to the target type, so int? x = flag ? 1 : null compiles and var does not. It cannot be a statement (CS0201).

solid answer

~50 s

`c ? a : b` first looks for a **natural type**: if one operand converts implicitly to the other's type, that type wins (`1` and `2.5` give `double`). If there is none, C# 9 added a **target-typed** fallback: when the destination type is known, each operand is converted to it, so `int? spaces = flag ? 12 : null;` and `IComparable k = flag ? 7 : "seven";` compile. With `var` there is no target, so `var x = flag ? 1 : null;` is CS0173. The natural type always wins when it exists, which is why `object o = flag ? 1 : 2.5;` holds a boxed `double`. And because it is an expression, `x > 0 ? open++ : closed++;` is CS0201: only assignment, call, increment, decrement, await and new object expressions can be statements, so side-effect branching belongs in an `if` statement.

code

csharp · 18 lines
csharp
bool cached = true;

object boxed = cached ? 1 : 2.5;          // natural type double wins
Console.WriteLine($"{boxed} is {boxed.GetType().Name}");

int? spaces = cached ? 12 : null;         // no natural type: target-typed (C# 9)
Console.WriteLine(spaces);

IComparable key = cached ? 7 : "seven";   // also target-typed
Console.WriteLine(key.GetType().Name);

Console.WriteLine(Fee.Describe(cached ? 1 : 2));

static class Fee
{
    public static string Describe(short units) => "short overload";
    public static string Describe(long units) => "long overload";
}

go deeper

for a junior

Know that only one operand of ?: runs, and that the result is a value: use it on the right of an assignment, and use if for side effects.

for a middle

Explain the natural type, the C# 9 target-typed fallback and why var gives CS0173, and recall CS0201 for a conditional used as a statement.

for a senior

Diagnose the surprises: a boxed double where an int was expected and an overload chosen by the natural type, and explain why the fallback ranks below every ordinary conversion.

for a principal

No lead-level decision rides on this; at most a style rule on nested conditionals and on preferring if when branches exist for side effects.

The **conditional operator** `condition ? consequent : alternative` evaluates a `bool` condition and then evaluates exactly one of the two operands; its result is that operand's value. It is the expression-level counterpart of an `if` statement, and two C# rules about it trip up experienced developers: how its **type** is chosen, and the fact that it is **not a statement**. ## How the type is chosen The compiler works through these steps: 1. **Natural type.** If the operands have a common type (one converts implicitly to the other's type), that type is the type of the whole expression. `flag ? 1 : 2.5` is a `double`; `flag ? "a" : null` is a `string`. 2. **Target type (C# 9 and later).** If there is no common type, or one operand cannot convert to it, and the expression appears where a type is expected (an assignment to a declared variable, a return, an argument), the compiler applies a *conditional expression conversion*: each operand is converted separately to the target type. 3. **Neither.** Without a common type and without a target, compilation fails with CS0173, "Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'". | code | result | |---|---| | `object o = flag ? 1 : 2.5;` | natural type `double`; `o` holds a boxed `double` and prints `1` | | `int? spaces = flag ? 12 : null;` | no natural type; target-typed to `int?` | | `IComparable key = flag ? 7 : "seven";` | no natural type; each operand converted to `IComparable` | | `var x = flag ? 1 : null;` | no natural type and no target: CS0173 | Before C# 9 the second and third lines failed; compiling them with `LangVersion` 8 still reports CS8957, which says a common type was not found and suggests language version 9.0 or greater. The usual workaround in older code was a cast on one operand, such as `flag ? 12 : (int?)null`. ## The natural type wins Target typing is a **fallback**, not an override. The design deliberately ranks any ordinary conversion above the conditional expression conversion, so that code written before C# 9 kept its meaning in almost every case (the known exception turns a previously valid call into an ambiguity error rather than silently changing it). Two consequences surprise people: - `object o = flag ? 1 : 2.5;` stores `1.0` as a `double`, not an `int`, because `double` is the natural type and boxing to `object` happens afterwards. - Given overloads `Describe(short)` and `Describe(long)`, the call `Describe(flag ? 1 : 2)` binds to `Describe(long)`: the natural type `int` converts to `long` by an ordinary implicit conversion, which beats the conditional expression conversion to `short`. Overload resolution in general is covered with method overloads. ## Why it cannot be a statement C# allows only certain expressions to stand alone as an **expression statement**. A line such as `x > 0 ? open++ : closed++;` fails with CS0201, "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement". The same error rejects `a + b;`. The conditional operator exists to produce a value; when the two branches exist for their side effects, write an `if` statement: - `if (x > 0) open++; else closed++;` states the intent and compiles. - Assigning the result is fine: `int delta = x > 0 ? 1 : -1;` is an assignment statement. - Discarding it (`_ = x > 0 ? A() : B();`) compiles, but reviewers rarely accept it as a replacement for `if`. ## Smaller rules worth knowing - Only one operand is evaluated, so `count > 0 ? total / count : 0` never divides by zero. - The operator is **right-associative**: `a ? b : c ? d : e` means `a ? b : (c ? d : e)`. Nested conditionals are legal but are often clearer as a switch expression, which belongs with pattern matching. - Inside an interpolated string the colon would start a format specifier, so `$"{open ? "up" : "down"}"` is CS8361; wrap it in parentheses: `$"{(open ? "up" : "down")}"`. - A user-defined type cannot overload `?:`. - `?:` is not the null-coalescing operator `??`, which is covered with the null-safety material, and its `ref` form (`c ? ref a : ref b`) belongs with ref locals.

  • In C#, how did code written before C# 9 make int? spaces = flag ? 12 : null compile?
    By giving the operands a common type: casting one of them, as in `flag ? 12 : (int?)null` or `flag ? (int?)12 : null`, or using `default(int?)`. Under C# 8 the uncast form reports CS8957, which says no common type was found between 'int' and '<null>' and suggests language version 9.0 or greater. Since C# 9 the target type `int?` makes the cast unnecessary.
  • In C#, why does Describe(flag ? 1 : 2) call Describe(long) rather than Describe(short)?
    The expression has a natural type, `int`. Converting `int` to `long` is an ordinary implicit conversion, while reaching `short` would need the C# 9 conditional expression conversion, and the language ranks any ordinary conversion above that one. That ranking was chosen so that calls like this one, written before C# 9, kept binding to the same overload.

  • Thinks target typing overrides the natural type, so object o = flag ? 1 : 2.5 boxes an int.
  • Says var x = flag ? 1 : null infers int? in C#.
  • Believes both operands of the conditional operator are always evaluated.
  • Thinks cond ? A() : B(); is a valid C# statement because it calls methods.
  • Believes int? x = flag ? 1 : null has always compiled in C#.