proposals/rejected/nullable-enhanced-common-type.md
Champion issue: https://github.com/dotnet/csharplang/issues/33
There is a situation in which the current common-type algorithm results are counter-intuitive, and results in the programmer adding what feels like a redundant cast to the code. With this change, an expression such as condition ? 1 : null would result in a value of type int?, and an expression such as condition ? x : 1.0 where x is of type int? would result in a value of type double?.
This is a common cause of what feels to the programmer like needless boilerplate code.
We modify the specification for finding the best common type of a set of expressions §11.6.3.15 to affect the following situations:
T and the other is a null literal, the result is of type T?.T? and the other is of a value type U, and there is an implicit conversion from T to U, then the result is of type U?.This is expected to affect the following aspects of the language:
M<T>(T a, T b) as M(1, null).More precisely, we change the following sections of the specification (insertions in bold, deletions in strikethrough):
Output type inferences
An output type inference is made from an expression
Eto a typeTin the following way:
- If
Eis an anonymous function with inferred return typeU(§11.6.3.13) andTis a delegate type or expression tree type with return typeTb, then a lower-bound inference (§11.6.3.10) is made fromUtoTb.- Otherwise, if
Eis a method group andTis a delegate type or expression tree type with parameter typesT1...Tkand return typeTb, and overload resolution ofEwith the typesT1...Tkyields a single method with return typeU, then a lower-bound inference is made fromUtoTb.- **Otherwise, if
Eis an expression with nullable value typeU?, then a lower-bound inference is made fromUtoTand a null bound is added toT. **- Otherwise, if
Eis an expression with typeU, then a lower-bound inference is made fromUtoT.- Otherwise, if
Eis a constant expression with valuenull, then a null bound is added toT- Otherwise, no inferences are made.
Fixing
An unfixed type variable
Xiwith a set of bounds is fixed as follows:
- The set of candidate types
Ujstarts out as the set of all types in the set of bounds forXi.- We then examine each bound for
Xiin turn: For each exact boundUofXiall typesUjwhich are not identical toUare removed from the candidate set. For each lower boundUofXiall typesUjto which there is not an implicit conversion fromUare removed from the candidate set. For each upper boundUofXiall typesUjfrom which there is not an implicit conversion toUare removed from the candidate set.- If among the remaining candidate types
Ujthere is a unique typeVfrom which there is an implicit conversion to all the other candidate types, thenXiis fixed toV.
- If
Vis a value type and there is a null bound forXi, thenXiis fixed toV?- Otherwise
Xiis fixed toV- Otherwise, type inference fails.
There may be some incompatibilities introduced by this proposal.
None.
None.