In C#, what do lifted operators return when an `int?` operand is null, and how do `==` and `!=` treat two nulls?
answer
- null in, null out
- equality returns a plain bool
- bool? is the exception
- unwrap at the edge
basics
~20 sLifted arithmetic and bitwise operators on int? return null when either operand is null, so age + 5 is null and never throws. Equality returns a plain bool: null == null is true and null != 5 is true.
solid answer
~50 sFor the operators a value type defines (`+`, `-`, `*`, `/`, `%`, unary `-`, `++`, the bitwise operators and user-defined operators on your own struct), C# also provides a *lifted* form on `T?`. The lifted form returns null when either operand is null and otherwise applies the original operator to the contained values, so `int? adjusted = age + 5;` is null for an empty `age`, and the result type is `int?`: assigning it to an `int` fails with CS0266. Equality is lifted differently: `==` and `!=` return a plain `bool`, `null == null` is `true`, and null compared with any value is unequal. `bool?` breaks the arithmetic rule on purpose: `&` and `|` use three-valued logic, so `null & false` is `false` and `null | true` is `true`, while `&&` and `||` do not compile on `bool?`. To stop null spreading, unwrap at the edge with `??` or `GetValueOrDefault`.
code
csharp · 24 linesusing System;
int? age = null;
int? bonusYears = 5;
Points? reward = null;
int? adjusted = age + bonusYears; // lifted +: null in, null out
Points? total = reward + new Points(10); // a user-defined + is lifted too
Console.WriteLine(adjusted is null); // True
Console.WriteLine(total is null); // True
Console.WriteLine(age == null); // True
Console.WriteLine(age != 30); // True
Console.WriteLine((age ?? 0) + bonusYears.GetValueOrDefault()); // 5
bool? consented = null;
Console.WriteLine(consented & false); // False
Console.WriteLine(consented | true); // True
Console.WriteLine((consented & true) is null); // True
readonly record struct Points(int Value)
{
public static Points operator +(Points a, Points b) => new(a.Value + b.Value);
}go deeper
Recall that arithmetic on an empty int? gives null instead of throwing, and that two empty int? values compare equal with ==.
Explain how the compiler lowers a lifted operator into flag tests, why the result type is T?, and why bool? & and | can still yield true or false.
Spot null travelling silently through a calculation, find where it entered, and convert at the boundary so the fallback is a reviewed decision.
Decide where unknown values are allowed to flow in shared models, and require explicit fallbacks at boundaries so reports never mix null-propagated and defaulted numbers.
## What "lifted" means A **lifted operator** is an operator the compiler derives for a nullable value type `T?` from an operator that `T` already has. It applies to the predefined unary and binary operators and to **user-defined operators** on your own structs. You write nothing: if `Points` declares `operator +(Points, Points)`, then `Points? + Points` compiles and uses it. The compiler lowers each lifted call to a `HasValue` test on each operand followed by the original operator on the payloads. ## How the compiler lowers it The compiler's lowering code (`LocalRewriter_BinaryOperator.cs` in Roslyn) documents the shape it emits for a lifted binary operator on temporaries `x` and `y`: 1. **Arithmetic**: `x.HasValue & y.HasValue ? new int?(x.GetValueOrDefault() + y.GetValueOrDefault()) : default(int?)`. Both flags are tested, the payloads are combined only when both are present, and the empty result is the default of `int?`. 2. **Equality**: `(x.GetValueOrDefault() == y.GetValueOrDefault()) & (x.HasValue == y.HasValue)`. Two empty values have equal payloads (both zero) and equal flags, so the result is `true`. 3. **Ordering** (`<`, `>`, `<=`, `>=`): `(x.GetValueOrDefault() < y.GetValueOrDefault()) & (x.HasValue & y.HasValue)`, which is `false` as soon as either flag is `false`. Constant operands are optimised further, but the semantics are these. Reading the three shapes side by side explains every row of the tables below. ## Arithmetic and bitwise operators For the arithmetic, bitwise and shift operators the rule is **null in, null out**: - `age + 5`, `age * 2`, `-age` and `age & 0xFF` are all `null` when `age` is empty; nothing throws. - `age++` on an empty `int?` leaves it empty. - The result type is `int?`, so `int total = age + 5;` fails with **CS0266**, "Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)". - A user-defined `+` on a struct is lifted the same way: `reward + new Points(10)` is null when `reward` is. Null travels silently: a survey statistic computed as `age + bonusYears` keeps flowing as null until something prints an empty string or an explicit cast throws, far from the operand that was missing. ## Equality is not null-in-null-out `==` and `!=` are lifted to return a plain `bool`, with null treated as a value of its own: | Expression, `age` empty | Result | |---|---| | `age == null` | `true` | | `age == otherEmptyAge` | `true` | | `age == 30` | `false` | | `age != 30` | `true` | Comparing a non-nullable `int` with `null` compiles, because both sides convert to `int?`, but the compiler reports **CS0472**: "The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'". That warning usually means a field was declared `int` where `int?` was intended. The ordering operators `<`, `>`, `<=` and `>=` also return a plain `bool`, and they return `false` whenever an operand is null, which is a separate trap with its own consequences for filtering. ## `bool?` uses three-valued logic For `bool?`, `&` and `|` do **not** follow the null-in-null-out rule. The result is non-null whenever the known operand decides it: | Expression, `consented` empty | Result | |---|---| | `consented & false` | `false` | | `consented & true` | `null` | | `consented \| true` | `true` | | `consented \| false` | `null` | | `!consented` | `null` | The short-circuiting `&&` and `||` are not defined for `bool?`: `a && b` fails with **CS0019**, "Operator '&&' cannot be applied to operands of type 'bool?' and 'bool?'". To branch on a `bool?`, write `if (consented == true)` or `if (consented is true)`. ## Stopping the propagation 1. **Unwrap at the edge**: `(age ?? 0) + bonusYears.GetValueOrDefault()` is a plain `int`, with every fallback visible. 2. **Keep the null deliberately** when "unknown" is the honest answer, and render it as such at output. 3. **Test once, compute plainly**: inside `if (age is int a)`, all arithmetic on `a` is ordinary `int` arithmetic with no lifting and no repeated flag checks. Lifting is convenient for a single expression, but every lifted operation repeats the flag test, and a long chain of them hides where the null came from. Converting at the boundary keeps both the cost and the meaning visible.
- Why does `int total = age + 5;` not compile when `age` is an `int?`?The lifted `+` returns `int?`, and there is no implicit conversion from `int?` to `int`, so the compiler reports CS0266. You must choose what null becomes: `(age ?? 0) + 5`, `age.GetValueOrDefault() + 5`, or an explicit cast that throws InvalidOperationException when `age` is empty.
- How do you write an `if` on a `bool?` such as `consented`?A `bool?` cannot be a condition directly, and `&&` and `||` do not compile on it (CS0019). Compare it with a constant, `if (consented == true)`, or use a pattern, `if (consented is true)`; both treat null as "not true". `consented ?? false` gives a plain `bool` when you want an explicit fallback.
- Does a struct need extra code for its own `+` to work on nullable operands?No. When a struct declares `operator +(Points, Points)`, the compiler lifts it automatically, so `Points? + Points?` compiles, returns `Points?`, and yields null if either side is null. The same applies to user-defined conversions between two value types.
- Adding 5 to a null int? throws InvalidOperationException
- null + 5 on an int? gives 5, treating null as zero
- null == null on two int? values is false
- A bool? with null makes every & and | result null
- You need to write a separate operator overload for MyStruct?
- int total = age + 5 compiles with a warning